sql - 查找同一列的 In 和 out
问题描述
我在下面有一个表格,系统给出了我不想要的输出和输出,但下面给出了所需的输出。
EmployeeID TrxType TrxDateTime
1 IN 20/07/2020 7:00
1 OU 20/07/2020 18:00
2 IN 21/07/2020 6:00
2 OU 21/07/2020 17:30
系统输出:-
employeeid date CheckIN CheckOUT
1 20.07.2020 NULL 20/07/2020 18:00
1 20.07.2020 20/07/2020 7:00 NULL
2 21.07.2020 NULL 21/07/2020 17:30
2 21.07.2020 21/07/2020 6:00 NULL
这是我使用的查询:
select distinct(TimeBooking.employeeid),(convert(nvarchar(10), TimeBooking.PunchDateTime, 104)) as date,
CheckIN = Max(case when TimeBooking.TrxType ='IN' then TimeBooking.trxDateTime END),
CheckOUT = MAX(CASE WHEN TimeBooking.TrxType = 'OU' THEN TimeBooking.trxDateTime END)
from TimeBooking where TimeBooking.TrxDateTime>='20-july-2020'
group by TimeBooking.TrxDateTime,employeeid
期望的输出:-
employeeid date CheckIN CheckOUT
1 20.07.2020 20/07/2020 7:00 20/07/2020 18:00
2 21.07.2020 21/07/2020 6:00 21/07/2020 17:30
解决方案
假设每个日期每个员工 ID 只有一行,只需使用聚合:
select employeeid, convert(date, TrxDateTime), min(TrxDateTime) as checkIN, max(TrxDateTime) as checkOUT
from t
group by employeeid, convert(date, TrxDateTime);
编辑:
如果每个员工每天有多行,您可以通过计数然后汇总来“对齐”它们:
select employeeid, dte,
min(case when trxType = 'IN' then TrxDateTime end) as checkIN,
max(case when trxType = 'OU' then TrxDateTime end) as checkOUT
from (select t.*, convert(date, t.TrxDateTime) as dte,
row_number() over (partition by t.employeeid, convert(date, t.TrxDateTime), t.trxType order by t.TrxDateTime) as seqnum
from t
) t
group by employeeid, dte, seqnum;
这是一个 db<>fiddle。
推荐阅读
- c# - 有没有办法使用 Quaternion.FromToRotation 来支持使用一个轴?
- generics - 密封类的通用对象
- php - 构建img src时文件名中的PHP空间
- javascript - 问jquery数组格式
- javascript - 使用时刻将时刻转换为格式(“H[h] m[m]”),但它显示的日期无效
- php - Laravel NeoEloquent 相当于 Inner Join
- php - 错误的结果 SoapVar
- java - 是否可以在 Android 中运行 H2O 模型?
- python - Flask 应用程序无法为请求创建 URL 适配器
- c# - 订阅多个 Observable 并在同一个线程上收到通知