开发者

sql group by where statement

开发者 https://www.devze.com 2023-01-07 19:47 出处:网络
lets say i have this table user|group|acceptance 1| a| -1 2| a| 2 3| b| 1 4| b开发者_运维知识库| 2

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

精彩评论

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