COUNT (Distinct Column) = 0 with GROUP BY

  • I have a table of users and date when they logged on to a system. I am trying to count how many distinct users logged on for each day of the week. The SQL below works when there's at least a user for each day. But when there is no user for a particular day such as Sunday, I still want it to return "SUN 0 "

    I learned that you can use GROUP BY ALL and it works but the "ALL" is deprecated beyond SQL 2005.

    ------------------------------------

    SELECT UPPER(LEFT(DATENAME(dw, StartTime), 3)) AS DayOfWeek,

    COUNT(DISTINCT UserID) AS NumberOfUser

    FROM testUserLoginDuration

    WHERE Archived = 0

    GROUP BY UPPER(LEFT(DATENAME(dw, StartTime), 3))

    ORDER BY

    CASE WHEN UPPER(LEFT(DATENAME(dw, StartTime), 3)) = 'MON' THEN 1

    WHEN UPPER(LEFT(DATENAME(dw, StartTime), 3)) = 'TUE' THEN 2

    WHEN UPPER(LEFT(DATENAME(dw, StartTime), 3)) = 'WED' THEN 3

    WHEN UPPER(LEFT(DATENAME(dw, StartTime), 3)) = 'THU' THEN 4

    WHEN UPPER(LEFT(DATENAME(dw, StartTime), 3)) = 'FRI' THEN 5

    WHEN UPPER(LEFT(DATENAME(dw, StartTime), 3)) = 'SAT' THEN 6

    WHEN UPPER(LEFT(DATENAME(dw, StartTime), 3)) = 'SUN' THEN 7

    END

    --------------

    returns

    MON 6

    TUE 3

    WED 5

    THU 3

    FRI 2

    SAT 1

  • Please don't cross post. It wastes people's time and scatters replies. Many of the regular readeers read all the forumns.

    Please direct any replies to the following thread.

    http://www.sqlservercentral.com/Forums/Topic472063-338-1.aspx

    Thanks

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply