如何仅选择唯一记录(基于标准)

时间:2015-03-02 18:38:22

标签: sql sql-server

我有一个基于某些条件选择数据的SQL Server查询,问题是这些数据中的一些是重复的。重复项只是具有重复CrewCodeCrewInvoiceAmounts的项目。

如何根据此条件仅返回唯一商品?

这是我到目前为止所拥有的:

SELECT DISTINCT
    PVDM_DOCS_1_16.docindex1 as CrewCode, 
    PVDM_DOCS_1_16.docindex5 as WorkOrder, 
    PVDM_DOCS_1_16.docindex8 as Amount, 
    PVDM_DOCS_1_16.docindex6 as BatchName, 
    PVDM_DOCS_1_16.docindex2 as CrewInvoice
FROM 
    PVDM_DOCS_1_16
INNER JOIN 
    PVDM_DOCS_1_4 ON PVDM_DOCS_1_16.DOCINDEX5=PVDM_DOCS_1_4.DOCINDEX1
WHERE
    PVDM_DOCS_1_16.docindex3 BETWEEN DATEADD(MONTH, -6, GETDATE()) AND GETDATE() 
    AND PVDM_DOCS_1_4.DOCINDEX9 != 'Phone' 
    AND ISNUMERIC(PVDM_DOCS_1_16.DOCINDEX8) = 1

1 个答案:

答案 0 :(得分:0)

每个项目的最大值是唯一的,按每个唯一项目分组。

SELECT DISTINCT
    Max(PVDM_DOCS_1_16.docindex1) as CrewCode, 
    Max(PVDM_DOCS_1_16.docindex5) as WorkOrder
    -- Removed to be shorter
FROM 
    PVDM_DOCS_1_16
INNER JOIN 
    PVDM_DOCS_1_4
ON 
    PVDM_DOCS_1_16.DOCINDEX5=PVDM_DOCS_1_4.DOCINDEX1
WHERE
    -- ...
Group By PVDM_DOCS_1_16.docindex1, PVDM_DOCS_1_16.docindex5 

我应该补充一点,您可能需要将where条款中的一个或多个更改为having条款。