首页 > 解决方案 > 不同表的多个案例

问题描述

我有一个这样的查询:

select U.Name,U.Adluserid as 'Empid', 
       min(case when IOType=0 then Edatetime end) as 'IN',
       max(case when IOType=1 then Edatetime end) as 'out'
       from Mx_ACSEventTrn
inner join Mx_UserMst U on Mx_ACSEventTrn.UsrRefcode=U.UserID
left join Tbl_Zeo_Empstatus E on  Mx_ACSEventTrn.UsrRefcode=E.Emp_Id
where cast(Edatetime as date) between '2019-10-30' and '2019-10-30' 
group by U.Name,U.Adluserid

输出

 Name            Empid     IN                          OUT                status           
JAS             505  2019-10-30 08:06:37.000    2019-10-30 14:13:29.000   Present
SAAJ            516  2019-10-30 08:05:11.000    2019-10-30 14:17:58.000   Absent
ram             516  2019-10-30 08:20:11.000    2019-10-30 14:17:58.000   Late

我有另一个这样的表:Tbl_Zeo_Empstatus

Emp_Id  Status
123      2
504      2
505      3

我怎样才能做到这一点?

标签: sqlsql-servercase

解决方案


您需要的是一个额外的查询级别(子选择),以便能够在聚合(最小和最大)上进行操作inout时间。为了能够连接您的数据,Tbl_Zeo_Empstatus我们需要提供外部查询,u.UserID然后基于该列执行左连接。

最终查询只需要一个CASE表达式来评估您的条件并根据in时间列设置预期状态。

select
  t.Name,
  t.Empid,
  t.t_in,
  t.t_out,
  case 
    when t.t_in is null and E.status = 2 then 'Absent'
    when t.t_in is null and E.status = 3 then 'Vacation'
    when cast(t.t_in as time) > '08:15' then 'Late' else 'Present' 
    end as status
from (
  select 
    u.UserID,
    u.Name,
    u.Adluserid as empid, 
    min(case when IOType=0 then Edatetime end) as t_in,
    max(case when IOType=1 then Edatetime end) as t_out,
  from 
    Mx_ACSEventTrn t
    inner join Mx_UserMst u on t.UsrRefcode = u.UserID
  where 
    cast(Edatetime as date) between '2019-10-30' and '2019-10-30' 
  group by 
    u.UserId, u.Name, u.Adluserid
) t
left join Tbl_Zeo_Empstatus e on t.UserID = e.Emp_Id

推荐阅读