Microsoft SQL Count问题

时间:2010-04-08 19:01:16

标签: sql sql-server count

嘿聪明人。我遇到以下SQL语句的问题。我知道我不能在OnlineStatus列上做GROUP BY,这是有意义的,因为它是一个函数调用,而不是我表中的实际列。我如何修改这个以便我可以计算有多少用户在线?

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

3 个答案:

答案 0 :(得分:8)

使用子查询做得最好:

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

答案 1 :(得分:2)

如果使用内部选择,它应该有效:

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

答案 2 :(得分:0)

您也可以将CASE WHEN移至COUNT

伪代码:

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