2014-09-19 69 views
1

我是新來的,所以請耐心等待。聚合,計數,案例和條款

我正在寫一個查詢,我需要用兩個特定的值來計算的行數,

我已經使用下列以獲得在一個領域的不同值的結果,但我需要知道僅當另一個字段設置爲特定值時纔會生成結果。我把從以前的問題,關於這個站點如下:

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

回答

1

你可以只添加條件到where條款:

COALESCE(count(case when CW.MAINJOBROLE = 2 and CW.EMPLSTATUS = 1 THEN 1 end),0) as ALLJOBROLES_2, 

順便說一下,COALESCE()應該是不必要的。如果沒有匹配,COUNT()將返回0

+0

謝謝我相信我試過這個,但必須讓我的括號不正確。 – 2014-09-22 08:51:03

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, 
.... 
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