【问题标题】:Combine two different rows in single table using same table in SQL Server使用 SQL Server 中的同一个表在单个表中组合两个不同的行
【发布时间】:2021-03-29 19:21:41
【问题描述】:
考虑一个包含这样数据的数据库表:
| Id |
UserId |
IsCheckIn |
DateTime |
Image |
AccountId |
| 30356 |
60866 |
1 |
2020-12-19 12:17:17 |
b622f3e0806f.jpg |
10017 |
| 30355 |
60866 |
0 |
2020-12-19 10:52:26 |
b622f3e0806f.jpg |
10017 |
| 30354 |
60866 |
1 |
2020-12-19 10:51:02 |
b622f3e0806f.jpg |
10017 |
| 30353 |
60866 |
0 |
2020-01-20 09:29:42 |
1596.jpg |
10017 |
期望的输出:
| Id |
UserId |
IsCheckIn |
InDateTime |
InImage |
AccountId |
IsCheckOut |
OutDateTime |
OutImage |
| 30356 |
60866 |
1 |
2020-12-19 12:17:17 |
b622f3e0806f.jpg |
10017 |
0 |
2020-12-19 10:52:26 |
b622f3e0806f.jpg |
| 30354 |
60866 |
1 |
2020-12-19 10:51:02 |
b622f3e0806f.jpg |
10017 |
0 |
2020-01-20 09:29:42 |
1596.jpg |
请帮忙
提前谢谢....
【问题讨论】:
标签:
sql
sql-server
database
datetime
【解决方案1】:
如果签入和签出始终正确交错,您可以使用lead():
select id, userid, ischeckin,
datetime as indatetime, image as inimage,
accountid,
lead_datetime as outdatetime, lead_image as outimage
from (
select t.*,
lead(datetime) over(partition by userid, accountid order by datetime) as lead_datetime,
lead(image) over(partition by userid, accountid order by datetime) as lead_image
from mytable t
) t
where ischeckin = 0
【解决方案2】:
看来您正在寻找类似的东西
select t.*, oa.*
from tTable t
outer apply (select top(1) tt.[DateTime] OutDateTime, tt.[Image]
from tTable tt
where tt.IsCheckIn=0
and t.[DateTime]<tt.[DateTime]
order by tt.[DateTime]) oa
where IsCheckIn=1;