sql-server - SQL Server Pivot 考勤记录根据 Time-In 和 Time-Out
问题描述
有人知道我怎样才能提出我的要求的解决方案吗?我有结构([ID],[DATE],[EMPID],[TIME])的考勤表。见下文:
ID DATE EMPID TIME REMARKS
1 20/09/2018 9001 7:30 This will be the In_1 as it is the first TIME-IN in for EMPID=9001
2 20/09/2018 9001 7:40 This will be the In_2 as it is the second TIME-IN for EMPID=9001
3 20/09/2018 9001 7:50 Not included
4 20/09/2018 9001 17:10 This will be the Out_1 as it is the first TIME-OUT for EMPID=9001
5 20/09/2018 9001 17:50 This will be the Out_2 as it is the second TIME-OUT for EMPID=9001
6 20/09/2018 9001 18:00 Not included
7 20/09/2018 9002 7:20 This will be the In_1 as it is the first TIME-IN in for EMPID=9002
8 20/09/2018 9002 7:21 This will be the In_2 as it is the second TIME-IN for EMPID=9002
9 20/09/2018 9002 18:00 This will be the Out_1 as it is the first TIME-OUT for EMPID=9002
10 20/09/2018 9003 7:00 This will be the In_1 as it is the first TIME-IN in for EMPID=9003
11 20/09/2018 9003 17:10 This will be the Out_1 as it is the first TIME-OUT for EMPID=9003
11 20/09/2018 9003 17:12 This will be the Out_2 as it is the second TIME-OUT for EMPID=9003
11 20/09/2018 9003 17:15 Not included
输出将与以下相同:
DATE EMPID IN_1 IN_2 OUT_1 OUT_2
20/09/2018 9001 7:30 7:40 17:10 17:50
20/09/2018 9002 7:20 7:21 18:00
20/09/2018 9003 7:20 17:10 17:12
解决方案
由于您没有可以从 OUT 中识别 IN 的列,因此我可以任意使用 12:00 作为分隔符时间。
; WITH
cte AS
(
SELECT *, TYPE = CASE WHEN TIME < '12:00' THEN 'IN' ELSE 'OUT' END
FROM your_table
),
cte2 AS
(
SELECT *, rn = row_number() over (partition by EMPID, DATE, TYPE ORDER BY TIME)
FROM cte
)
SELECT DATE, EMPID,
IN_1 = MAX(CASE WHEN TYPE = 'IN' AND rn = 1 THEN TIME END),
IN_2 = MAX(CASE WHEN TYPE = 'IN' AND rn = 2 THEN TIME END),
OUT_1 = MAX(CASE WHEN TYPE = 'OUT' AND rn = 1 THEN TIME END),
OUT_2 = MAX(CASE WHEN TYPE = 'OUT' AND rn = 2 THEN TIME END)
FROM cte2
GROUP BY DATE, EMPID
推荐阅读
- python - 使用 Python SDK 在 Azure 中创建虚拟机的用户名
- git - 从 git stash 返回到预览状态和提交中的顺序
- coldfusion - ColdFusion 8 中的过滤系统
- javascript - 如何将此类数据从站点发送到服务器?
- typescript - 为什么变量类型变成any?
- bash - 如何按应用的最新日期获取最新补丁列表 rpm -qa -last 命令
- python - Python pandas - 升级到 1.1.0 后损坏的 groupby 和排序
- java - 如何使用 Spring MVC 和 Thymeleaf 按 ID 搜索 OBJ?
- linux - 如何使用别名在bash文件中调用别名?
- c# - ASP.NET WebAPI 和 Angular 集成。未找到集合