考虑以下表结构和示例数据 -
EmpID InputDateTime StatusINOUT
-------------------------------------
1 2018-05-26 08:44 1
1 2018-05-26 08:44 2
2 2018-05-28 08:44 1
2 2018-05-28 12:44 2
1 2018-05-21 08:44 1
1 2018-05-21 10:44 2
2 2018-05-23 08:44 1
2 2018-05-23 08:44 2
现在我想分隔列InputDateTime
分为两列,即 INTIME(1)
和OUTTIME(2)
。这背后的逻辑是 StatusInOut
的日期为 1 将是 InTime
和 StatusInOut
为 2 时日期值为 OUTTIME(2)
.
预期的输出格式如下所示:
Empid INTIME(1) OUTIME(2)
--------------------------------------------
1 2018-05-26 08:44 2018-05-26 08:44
2 2018-05-28 08:44 2018-05-28 12:44
1 2018-05-21 08:44 2018-05-21 10:44
2 2018-05-23 08:44 2018-05-23 08:44
这是我迄今为止尝试过的
create table #tempStatus (EmpId int, intTime datetime, sStatus int)
insert into #tempStatus
values(1, '2018-05-26 08:44', 1),
(1, '2018-05-26 08:44', 2),
(2, '2018-05-28 08:44', 1),
(2, '2018-05-28 12:44', 2),
(1, '2018-05-21 08:44', 1),
(1, '2018-05-21 10:44', 2),
(2, '2018-05-23 08:44', 1),
(2, '2018-05-23 08:44', 2)
select EmpId, MIN(intTime) as intTime, MIN(intTime) as OutTime into #tempA from (
select EmpId, intTime, intTime as OutTime
from #tempStatus where sStatus = 1
)a
group by EmpId, intTime
select EmpId, MAX(outTime) as outTime into #tempB from(
select EmpId, intTime as outTime
from #tempStatus where sStatus = 2
)b
group by empId,outTime
select * from #tempA order by EmpId
drop table #tempA
drop table #tempB
DROP TABLE #tempStatus
最佳答案
您需要row_number()
并使用它们的差异来进行条件聚合,这也称为间隙和岛屿
问题:
select empid,
max(case when sStatus = 1 then intTime end) as INTIME,
max(case when sStatus = 2 then intTime end) as OUTIME
from (select t.*,
row_number () over ( order by inttime) as seq1,
row_number () over (partition by empid order by inttime) as seq2
from #tempStatus t
) t
group by empid, (seq1-seq2);
编辑:如果您想在 InTime
不存在时显示 OutTime
,那么您可以使用子查询:
select t.empid,
coalesce(INTIME, OUTIME) as INTIME,
coalesce(OUTIME, INTIME) as OUTIME
from ( <query here>
) t;
关于sql - 如何将数据分成两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53832254/