sql group by where语句

时间:2010-07-20 02:35:10

标签: sql sql-server-2005

让我说我有这张桌子

user|group|acceptance
1   | a   | -1
2   | a   | 2
3   | b   | 1
4   | b   | 2
5   | b   | 2
6   | c   | -1

我如何计算每组中有多少用户接受不是-1,但仍列出有0计数的组

所以结果就像

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

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

Count(Col)不计算NULL值。因此传递一个非空值,其中接受<> -1(对于未处理的情况,它将默认为传递null)

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