sql COUNT个问题

时间:2011-03-18 12:40:34

标签: sql count

如何修改此查询以返回排除所有具有重复DocNum的记录的结果?

SELECT IdEntry, DocNum, CardCode, QUOTENAME(CardName,'"'), 
Convert(Decimal(10,2),PayAmount), Convert(Decimal(10,2),InvPayAmnt), 
CONVERT(VARCHAR(10), T5.PmntDate,101), NumAtCard, PymMeth, ObjType
FROM DELAWARE.dbo.PWZ3
INNER JOIN OPWZ T5 ON T5.IdNumber = IdEntry
WHERE T5.PmntDate = '3/10/2011' 
AND T5.Canceled = 'N' 
AND Checked = 'Y'

3 个答案:

答案 0 :(得分:1)

尝试

WITH
    dups (DocNum)
    AS (
        SELECT DocNum
        FROM DELAWARE.dbo.PWZ3
        GROUP BY DocNum
        HAVING COUNT(1) > 1
    )
SELECT PWZ3.IdEntry, PWZ3.DocNum, PWZ3.CardCode, QUOTENAME(CardName,'"'), 
Convert(Decimal(10,2),PayAmount), Convert(Decimal(10,2),InvPayAmnt), 
CONVERT(VARCHAR(10), T5.PmntDate,101), NumAtCard, PymMeth, ObjType
FROM DELAWARE.dbo.PWZ3 PWZ3
INNER JOIN OPWZ T5 ON T5.IdNumber = PWZ3.IdEntry
LEFT JOIN Dups ON DUPS.DocNum = PWZ3.DocNum
WHERE T5.PmntDate = '3/10/2011' 
AND T5.Canceled = 'N' 
AND Checked = 'Y'
AND Dups.DocNum is null

(我可能没有正确的所有列别名)

答案 1 :(得分:0)

我不确定我是否了解所有查询,但不是一个简单的

 SELECT ... GROUP BY docNum

足够?

答案 2 :(得分:0)

SELECT IdEntry, DocNum, CardCode, QUOTENAME(CardName,'"'), 
Convert(Decimal(10,2),PayAmount), Convert(Decimal(10,2),InvPayAmnt), 
CONVERT(VARCHAR(10), T5.PmntDate,101), NumAtCard, PymMeth, ObjType

FROM DELAWARE.dbo.PWZ3
INNER JOIN OPWZ T5 ON T5.IdNumber = IdEntry

JOIN (SELECT min(IdEntry) as minIdEntry from DELAWARE.dbo.PWZ3 group by DocNum) tmp on DELAWARE.dbo.PWZ3.IdEntry = minIdEntry

WHERE T5.PmntDate = '3/10/2011' 
AND T5.Canceled = 'N' 
AND Checked = 'Y'