2016-02-08 148 views
0

我具有以下表:多個條件

僱員終止ID員工狀態日期 1所述的NULL 2所述的NULL 3 I 2016年1月1日 4 I 2016年12月15日 5 I 2016年1月1日

enter image description here

我想就以下報告:

  • 當前活動僱員數量 - 2
  • 非活動僱員數量 - 3
  • 在最後1個月終止僱員數量 - 2

這是一塊我使用的代碼:

select 
case when employee_status='A' then count(employee_id) else '' end, 
case when employee_status='I' then count(employee_id) else '' end, 
case when employee_status='I' 
then 
(select count(employee_id) 
    from employee 
where date_of_termination between '1/1/2016' and '2/1/2016') 
else '' end 
from employee 

我的結果集爲:

Active | Inactive | Inactive_last_month 
    2 |  0 |     0 
    0 |  3 |     2 

我想實現以下目標:

Active | Inactive | Inactive_last_month 
    2 |  3 |     2 

任何建議,將不勝感激。

回答

0

這應該是能夠利用SUM簡化它:

select 
sum(case when employee_status='A' then 1 else 0 end) as active, 
sum(case when employee_status='I' then 1 else 0 end) as inactive, 
sum(case when employee_status='I' and date_of_termination between '1/1/2016' and '2/1/2016' then 1 else 0 end) as inactive_last_month 
from employee 
+0

這工作。謝謝。 – Anonymous

0

我woudl包裹的情況下在satements sum()函數,並且還修改CASE語句的ELSE部分爲0

所以它看起來像這樣的事情:

select 
SUM(case when employee_status='A' then count(employee_id) else 0 end) AS Active, 
SUM(case when employee_status='I' then count(employee_id) else 0 end) AS Inactive, 
SUM(case when employee_status='I' 
then 
(select count(employee_id) 
    from employee 
where date_of_termination between '1/1/2016' and '2/1/2016') 
else 0 end) AS Inactive_last_month 
from employee 
+0

謝謝。您的查詢中有一個額外的「總和」,我編輯了它,並且它啓動得很好。謝謝。 – Anonymous

+0

@匿名很高興幫助!我刪除了額外的SUM() –

0

您需要SUM了相互匹配條件的行數:

SELECT 
    SUM(CASE WHEN date_of_termination IS NULL THEN 1 ELSE 0 END) AS active, 
    SUM(CASE WHEN date_of_termination IS NOT NULL THEN 1 ELSE 0 END) AS inactive, 
    SUM(CASE WHEN date_of_termination BETWEEN '20160101' AND '20160201' THEN 1 ELSE 0 END) AS inactive_last_month 
FROM 
    Employee 

我忽略了employee_status列在假設日期是足以確定員工是否爲有效/無效 - 在這種情況下,該列可能甚至不應該存在於表中,因爲它的複製數據。

+1

一些員工是rehires,他們有不同的地位,因此需要列。但是聚合很有幫助。謝謝。 – Anonymous