避免重复行到SUM两次

时间:2017-11-22 19:49:17

标签: sql sql-server sum duplicates

我有一个包含重复行的表,如何将该重复行作为不同的值进行求和?我知道我可以将不同的数据插入到一个新表中,并以这种方式求和,但我试图避免创建任何类型的表。 表:

SELECT '123' DateID,'8' HOUR,'6000' AMT, '20150801' PayEndingDate, '20150807' CheckDate
INTO #DATA
UNION ALL
SELECT '456',8,'6000','20150801','20150807' UNION ALL
SELECT '789',8,'6000','20150801','20150807' UNION ALL --DUP ROW
SELECT '789',8,'6000','20150801','20150807' UNION ALL --DUP ROW
SELECT '987',8,'6000','20150725','20150807' UNION ALL
SELECT '654',8,'6000','20150725','20150807' UNION ALL
SELECT '321',8,'6000','20150725','20150807' UNION ALL --DUP ROW
SELECT '321',8,'6000','20150725','20150807' --DUP ROW
SELECT * FROM #DATA

|DateID | HOUR  | AMT      | PayEndingDate  | CheckDate
 123      8       6000       20150801         20150807
 456      8       6000       20150801         20150807
 789      8       6000       20150801         20150807
 789      8       6000       20150801         20150807
 987      8       6000       20150725         20150807
 654      8       6000       20150725         20150807
 321      8       6000       20150725         20150807
 321      8       6000       20150725         20150807

SELECT  DISTINCT SUM(HOUR) AS HOURS, AMT, PayEndingDate, CHECKDATE
FROM #DATA
GROUP BY AMT,PayEndingDate,CHECKDATE

| HOUR  | AMT      | PayEndingDate  | CheckDate
  32      6000       20150725         20150807
  32      6000       20150801         20150807

正如您所看到的,ID 321789是重复的并且导致小时数为32而不应该是24.在SUM中添加不同的内容只返回8.如何在这种情况下避免重复?

2 个答案:

答案 0 :(得分:3)

试试这个......

Select SUM(HOUR) AS HOURS, AMT, PayEndingDate, CHECKDATE
From (
SELECT  DISTINCT DateID, HOUR , AMT, PayEndingDate, CHECKDATE
FROM #DATA
) A
GROUP BY AMT,PayEndingDate,CHECKDATE

答案 1 :(得分:2)

DISTINCT可能有点贵。就个人而言,我更喜欢使用A CTE和ROW_NUMBER:

WITH CTE AS(
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY DateID ORDER BY DateID) AS RN
    FROM #Data)
SELECT SUM(HOUR) AS HOURS, AMT, PayEndingDate, CHECKDATE
FROM CTE
WHERE RN = 1
GROUP BY AMT, PayEndingDate, CHECKDATE;