如何摆脱每一行中的重复数据?

时间:2017-10-30 06:40:56

标签: sql sql-server tsql

        SELECT distinct AD.ReferenceNumber, AD.ProjectTitle, Z.ZoneCode, C.CompanyName,SS.AssignedTo, ZG.ZoneGroupName,au.Amount
        FROM ApplicationDetails AD
        LEFT JOIN ApplicationFormsDetails AS b ON (AD.referencenumber = b.referencenumber)
        LEFT JOIN ScheduleSummaries AS SS ON (AD.ReferenceNumber = SS.ReferenceNo)
        INNER JOIN AppTypes as at on ss.ItemCode = at.Category
        INNER JOIN Companies AS C ON (AD.CompanyId = C.CompanyID)
        INNER JOIN Zones Z ON (C.ZoneCode = Z.ZoneCode)
        INNER JOIN ZoneGroups ZG ON (Z.ZoneGroup = ZG.ZoneGroupId)
        LEFT JOIN AssessmentUsedItems au on ah.AssessmentHeaderId = au.HeaderId
        WHERE AD.ApplicationDate BETWEEN '2017-10-01' AND '2017-10-31' AND ZG.ZoneGroupCode = 'HO' and ah.referencenumber = 'N-101317-A1-02'
        GROUP BY AD.ReferenceNumber, AD.ProjectTitle, Z.ZoneCode, C.CompanyName,SS.AssignedTo, ZG.ZoneGroupName,au.Amount--, ah.ApplicationForm,au.Amount

此查询的输出是重复每个AssignTO的数量。

输出:

enter image description here

2 个答案:

答案 0 :(得分:0)

也许你想尝试使用SUM(ISNULL(au.amount, 0)) AS amount代替au.amount,并从au.amount移除GROUP BY ......

答案 1 :(得分:0)

尝试此查询:

SELECT AD.ReferenceNumber,
       AD.ProjectTitle,
       Z.ZoneCode,
       C.CompanyName,
       SS.AssignedTo,
       ZG.ZoneGroupName,
       SUM(COALESCE(au.Amount,0)) AS Amount
FROM   ApplicationDetails AD
       LEFT JOIN ApplicationFormsDetails  AS b
            ON  (AD.referencenumber = b.referencenumber)
       LEFT JOIN ScheduleSummaries        AS SS
            ON  (AD.ReferenceNumber = SS.ReferenceNo)
       INNER JOIN AppTypes                AS at
            ON  ss.ItemCode = at.Category
       INNER JOIN Companies               AS C
            ON  (AD.CompanyId = C.CompanyID)
       INNER JOIN Zones Z
            ON  (C.ZoneCode = Z.ZoneCode)
       INNER JOIN ZoneGroups ZG
            ON  (Z.ZoneGroup = ZG.ZoneGroupId)
       LEFT JOIN AssessmentUsedItems au
            ON  ah.AssessmentHeaderId = au.HeaderId
WHERE  AD.ApplicationDate BETWEEN '2017-10-01' AND '2017-10-31'
       AND ZG.ZoneGroupCode = 'HO'
       AND ah.referencenumber = 'N-101317-A1-02'
GROUP BY
       AD.ReferenceNumber,
       AD.ProjectTitle,
       Z.ZoneCode,
       C.CompanyName,
       SS.AssignedTo,
       ZG.ZoneGroupName