首页 > 解决方案 > 将两个连续的行合并为一列

问题描述

假设,我有一张这样的桌子:

员工代码 入口类型 时间
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 服务器查询来实现这一点?

提前致谢。

标签: sqlsql-servertsql

解决方案


提供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

否则首先需要进行某种清理。


推荐阅读