views:

88

answers:

3

Hey smarties. I'm having trouble with the following SQL statement. I know that I can't do a GROUP BY on the OnlineStatus column, and it makes sense because it's a function call, not an actual column in my table. How would I modify this so that I can get a count of how many users are online?

SELECT CASE dbo.fnGetWebUserOnlineStatus(W.Id) 
        WHEN 1 THEN 'Online' 
        WHEN 2 THEN 'Ingame' 
        ELSE 'Offline' 
       END AS OnlineStatus
FROM dbo.WebUsers W
WHERE W.[Status]=1
GROUP BY OnlineStatus
+8  A: 

That's best done using a subquery:

SELECT OnlineStatus, count(*)
FROM (
    SELECT  CASE dbo.fnGetWebUserOnlineStatus(W.Id) 
        WHEN 1 THEN 'Online' 
        WHEN 2 THEN 'Ingame' 
        ELSE 'Offline' 
         END AS OnlineStatus
    FROM dbo.WebUsers W
    WHERE W.[Status]=1
) sub
GROUP BY OnlineStatus
Andomar
+1, exactly what I was thinking
KM
Perrrrrrrrrrrfect!!
Matt
Well, Mat, give Andomar his "Answer" then...(even if he doesn't really need it, with THAT much points :)
iDevlop
+2  A: 

It should work if you use an inner select:

SELECT OnlineStatus, COUNT(*)
FROM (
    SELECT  CASE dbo.fnGetWebUserOnlineStatus(W.Id) 
                WHEN 1 THEN 'Online' 
               WHEN 2 THEN 'Ingame' 
               ELSE 'Offline' 
           END AS OnlineStatus
           FROM dbo.WebUsers W
           WHERE W.[Status]=1
) AS T1
GROUP BY OnlineStatus
Mark Byers
+1, missed it by a few seconds...
KM
A: 

You could also move the CASE WHEN into the COUNT

Pseudo code:

SELECT 
    COUNT(CASE dbo.fnGetWebUserOnlineStatus(W.Id) WHEN 1 THEN 1 ELSE NULL END) as OnlineCount,
    COUNT(CASE dbo.fnGetWebUserOnlineStatus(W.Id) WHEN 2 THEN 1 ELSE NULL END) as IngameCount ...
FROM dbo.WebUsers W 
WHERE W.[Status]=1
dalo