我是新手,所以请多多包涵。
我正在编写一个查询,我需要计算具有两个特定值的行数,
我已使用以下方法获取一个字段中不同值的结果,但仅当另一个字段设置为特定值时我才需要知道结果。我从本网站上一个问题中提取了以下内容:
COALESCE(count(case when CW.MAINJOBROLE = 2 THEN 1 end),0) as ALLJOBROLES_2,
coalesce(count(case when CW.MAINJOBROLE = 3 then 1 end), 0) as ALLJOBROLES_3,
coalesce(count(case when CW.MAINJOBROLE = 4 then 1 end), 0) as ALLJOBROLES_4,
coalesce(count(case when CW.MAINJOBROLE = 7 then 1 end), 0) as ALLJOBROLES_7,
coalesce(count(case when CW.MAINJOBROLE = 8 then 1 end), 0) as ALLJOBROLES_8,
coalesce(count(case when CW.MAINJOBROLE = 23 then 1 end), 0) as ALLJOBROLES_23,
coalesce(count(case when CW.MAINJOBROLE = 24 then 1 end), 0) as ALLJOBROLES_24,
coalesce(count(case when CW.MAINJOBROLE = 25 then 1 end), 0) as ALLJOBROLES_25'
作为更大查询的一部分,我只想在 CW.EMPLSTATUS = 1
最佳答案
您可以将条件添加到 where
子句中:
COALESCE(count(case when CW.MAINJOBROLE = 2 and CW.EMPLSTATUS = 1 THEN 1 end),0) as ALLJOBROLES_2,
顺便说一下,COALESCE()
应该是不必要的。如果没有匹配项,COUNT()
将返回 0
。
关于sql - 将合并、计数、案例和子句组合在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25932692/