开发者

sql group by where statement

lets say i have this table

user|group|acceptance
1   | a   | -1
2   | a   | 2
3   | b   | 1
4   | b开发者_运维知识库   | 2
5   | b   | 2
6   | c   | -1

how do i get count how many users in each group have acceptance not -1 but still list the group having 0 count

so result would be like

group | count
a     | 1
b     | 3
c     | 0

thanks for the help


SELECT [group], SUM(CASE acceptance WHEN -1 THEN 0 ELSE 1 END) AS [count]
FROM MyTable
GROUP BY [group]


Count(Col) doesn't count NULL values. So pass a non null value where acceptance <> -1 (and it will default to passing null for the case not handled)

SELECT [group], 
       COUNT(CASE WHEN acceptance <> -1 THEN 1 END) AS [count] 
FROM tbl
GROUP BY [group]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜