sql - 将两个连续的行合并为一列
问题描述
假设,我有一张这样的桌子:
员工代码 | 入口类型 | 时间 |
---|---|---|
ABC200413 | 在 | 上午 8 点 48 分 |
ABC200413 | 出去 | 下午 4:09 |
ABC200413 | 在 | 下午 4 点 45 分 |
ABC200413 | 出去 | 下午 6:09 |
ABC200413 | 在 | 晚上 7 点 45 分 |
ABC200413 | 出去 | 晚上 10:09 |
现在我想将我的数据转换成这样:
员工代码 | IN_TIME | 时差 |
---|---|---|
ABC200413 | 上午 8 点 48 分 | 下午 4:09 |
ABC200413 | 下午 4 点 45 分 | 下午 6:09 |
ABC200413 | 晚上 7 点 45 分 | 晚上 10:09 |
有什么方法可以使用 SQL 服务器查询来实现这一点?
提前致谢。
解决方案
提供mytable
的仅包含有效的输入/输出事件对
select EmployeeCode,
max(case EntryType when 'IN' then TIME end ) IN_TIME,
max(case EntryType when 'OUT' then TIME end ) OUT_TIME
from (
select EmployeeCode, EntryType, TIME,
row_number() over(partition by EmployeeCode, EntryType order by TIME) rn
from mytable
)t
group by EmployeeCode, rn
order by EmployeeCode, rn
否则首先需要进行某种清理。
推荐阅读
- c# - 在 ABP 框架中运行单元测试时发生 System.ObjectDisposedException
- php - 如何从选项中获取所选元素的ID
- json - Angular 6 定义日期的 JSON 格式
- ios - 如何在按钮单击时过滤 tableView 单元格,如果单元格文本字段在 swift 中具有按钮名称的字符串
- vba - excel中的可点击图表
- xtext - Xtext 全局自动生成
- python - Keras 继承内置层?
- node.js - NodeJS 路由器有效负载太大
- amazon-web-services - 通过堡垒主机访问 RDS,端口转发不起作用
- javascript - ASP.NET MVC Ajax 提交带有 AntiforgeryToken 的表单和带有验证的序列化表单数据