我是新手,所以请耐心等待。
我正在编写一个查询,我需要计算具有两个特定值的行数,
我使用以下内容在一个字段中获取不同值的结果,但只有在另一个字段设置为特定值时才需要知道结果。我从本网站上一个问题中提取了以下内容:
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
答案 0 :(得分:1)
您可以将条件添加到where
子句中:
COALESCE(count(case when CW.MAINJOBROLE = 2 and CW.EMPLSTATUS = 1 THEN 1 end),0) as ALLJOBROLES_2,
顺便说一句,COALESCE()
应该是不必要的。如果没有匹配项,COUNT()
将返回0
。
答案 1 :(得分:0)
您必须使用另一个CASE WHEN构造包围每个表达式:
CASE WHEN CW.EMPLSTATUS = 1 THEN
count(case when CW.MAINJOBROLE = 2 THEN 1 end)
ELSE
NULL
END as ALLJOBROLES_2,
CASE WHEN CW.EMPLSTATUS = 1 THEN
count(case when CW.MAINJOBROLE = 3 THEN 1 end)
ELSE
NULL
END as ALLJOBROLES_3,
....
答案 2 :(得分:0)
我相信你想使用SUM()而不是COUNT()。
SUM(case when CW.EMPLSTATUS = 1 AND CW.MAINJOBROLE = 2 THEN 1 end) as ALLJOBROLES_2,
SUM(case when CW.EMPLSTATUS = 1 AND CW.MAINJOBROLE = 3 then 1 end) as ALLJOBROLES_3,
SUM(case when CW.EMPLSTATUS = 1 AND CW.MAINJOBROLE = 4 then 1 end) as ALLJOBROLES_4,
SUM(case when CW.EMPLSTATUS = 1 AND CW.MAINJOBROLE = 7 then 1 end) as ALLJOBROLES_7,
SUM(case when CW.EMPLSTATUS = 1 AND CW.MAINJOBROLE = 8 then 1 end) as ALLJOBROLES_8,
SUM(case when CW.EMPLSTATUS = 1 AND CW.MAINJOBROLE = 23 then 1 end) as ALLJOBROLES_23,
SUM(case when CW.EMPLSTATUS = 1 AND CW.MAINJOBROLE = 24 then 1 end) as ALLJOBROLES_24,
SUM(case when CW.EMPLSTATUS = 1 AND CW.MAINJOBROLE = 25 then 1 end) as ALLJOBROLES_25