sql - 不同表的多个案例
问题描述
我有一个这样的查询:
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
我想根据这个条件显示状态列。如果 IN 时间不为空,则检查时间是否超过 8.15 AM。如果超过 8.15 AM,则显示较晚,否则显示存在。
如果时间为空,则从此表“Tbl_Zeo_Empstatus”中检查员工的状态,如果状态 2 则显示“缺席”,如果状态 3 则显示“假期”,如下所示。
我怎样才能做到这一点?
解决方案
您需要的是一个额外的查询级别(子选择),以便能够在聚合(最小和最大)上进行操作in
和out
时间。为了能够连接您的数据,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
推荐阅读
- python - 在 Python 中缩短条件
- excel - How to write formula to display how many times one word is present in a row in ratio?
- javascript - 由用户输入从下拉选项框中添加和删除
- c++ - 使用 C++ 在 Visual Studio 2017 中“项目引用”有什么作用?
- c# - C#中的多个通配符
- qt - QT 框架安装程序 - 如何强制 targetDir
- javascript - 在 html 代码中添加字符串变量
- r - 为 selectInput R Shiny 中的每个选定选项传递多个值
- javascript - 为什么函数长度不包括其余参数
- java - 如果 Predicate 有多个抽象方法,它怎么能成为一个功能接口?