有特定条件的计数列
问题描述:
我如何计算保存特定值的列 - 但将其作为总计。有特定条件的计数列
表中的数据:
Code No
1 *
2 -
3 4
4
举例来说,如果我想看看有多少行有*和 - 和空间
我能做
Case when No = '*'
Then COUNT(No)
when No = '-' then count(No)
when No = '' then count(No)
else 0 end as 'Count'
但这返回4
http://sqlfiddle.com/#!9/f73409/4
我想这回3
任何帮助,将不胜感激
答
标准SQL有一个特定的功能:filter
子句遵循聚合。
不幸的是,它没有得到广泛的支持(主要是PostgreSQL)。
有一个简单的解决方案使用case
但是:
COUNT(CASE WHEN <condition> THEN 1 END)
这工作,因为case
因为count
隐含else null
条款不计null
。
更多关于filter
条款及其模仿方法:http://modern-sql.com/feature/filter