SQL中的多个条件

时间:2016-02-08 17:23:07

标签: sql case

我有以下表格:

员工ID员工身份终止日期 1个NULL 2一个NULL 3 I 1/1/2016 4 I 12/15/2016 5 I 1/1/2016

enter image description here

我想报告以下内容:

  
      
  • 现有在职员工人数 - 2
  •   
  • 非活动员工人数 - 3
  •   
  • 过去一个月终止的员工人数 - 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

任何建议都将受到赞赏。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我将在sum()函数中包装case satements,并将CASE Statement的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

答案 2 :(得分: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列,并假设日期足以确定员工是否处于活动/非活动状态 - 在这种情况下,该列可能甚至不存在表格,因为它复制了数据。