Friday, September 21, 2012

GROUP BY and DISTINCT

DECLARE @Team TABLE(EventDate DATETIME, Seconds BIGINT)

INSERT INTO @Team
SELECT '2012-08-25',440 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',1232 UNION ALL
SELECT '2012-08-25',7740 UNION ALL
SELECT '2012-08-25',18640 UNION ALL
SELECT '2012-08-25',18640 UNION ALL
SELECT '2012-08-25',18640 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512 UNION ALL
SELECT '2012-08-25',512

SELECT EventDate, Seconds FROM @Team

Sum the column Seconds for the group EventDate
SELECT EventDate, SUM(Seconds) Seconds
FROM @Team
GROUP BY EventDate
The value in the column Seconds is summed with the duplicate value.


How to sum the column without duplicate
SELECT EventDate, Sum(DISTINCT Seconds) Seconds 
FROM     @Team 
GROUP BY EventDate

SELECT   EventDate, Sum(Seconds) AS Seconds 
FROM     ( SELECT EventDate, Seconds 
                  FROM @Team 
                  GROUP BY EventDate, Seconds ) AS T 
GROUP BY EventDate

SELECT   EventDate, Sum(Seconds) AS Seconds 
FROM     ( SELECT DISTINCT EventDate, Seconds 
           FROM @Team ) AS T 
GROUP BY EventDate

No comments: