CASE WHEN COUNT and GROUP BY

Greetings...I have the following statement that produces the expected results of id, Name and Points. However, I would like to 'sum' the count where names are duplicates. In other words, if a name has two entries (each having Points=1) I would like one entry where Points=2.

If I uncomment my GROUP BY I get only one name, but the Points value remains 1. What am I doing wrong? Thanks...Scott

SELECT b.[id],
            b.[Name],
            CASE WHEN ((TrackingDateTime) IS NOT NULL AND (ReceivedByHESDateTime) IS NOT NULL) THEN 1 ELSE 0 END AS Points
      FROM DocumentTracking a
      INNER JOIN companies b ON (a.companyid = b.[id])
      WHERE TrackingDateTime >= '10/28/03'
            AND TrackingDateTime <= '10/28/04'
      --GROUP BY b.[id], b.[name]
      ORDER BY b.[name]
rsanglimAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
HilaireConnect With a Mentor Commented:
try

SELECT b.[id],
          b.[Name],
          SUM(CASE WHEN ((TrackingDateTime) IS NOT NULL AND (ReceivedByHESDateTime) IS NOT NULL) THEN 1 ELSE 0 END) AS Points
     FROM DocumentTracking a
     INNER JOIN companies b ON (a.companyid = b.[id])
     WHERE TrackingDateTime >= '10/28/03'
          AND TrackingDateTime <= '10/28/04'
     GROUP BY b.[id], b.[name]
     ORDER BY b.[name]
0
 
HilaireCommented:
I just added a SUM group function to collapse the records that belong to the same group into one single record
0
 
Julian HansenCommented:
I think Hilaire has nailed it.

The GROUP BY works with the agregate functions SUM, MAX, MIN etc without specifying an agregate function SQL does not know what you want to do - i.e. it cannot know that you want to sum the points - you might want to find the MAX or the MIN.


0
[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

 
rsanglimAuthor Commented:
Thanks, Hilaire...that was it! I appreciate the quick reply :)
0
 
rsanglimAuthor Commented:
...and thanks julian for the explanation!
0
 
Julian HansenCommented:
;) you are most welcome
0
All Courses

From novice to tech pro — start learning today.