gpt4 book ai didi

mysql - T-SQL 分组/合并记录

转载 作者:行者123 更新时间:2023-11-29 12:22:53 24 4
gpt4 key购买 nike

我有一个事件表,它包含“开始”和(以及许多其他)“结束”事件。

person, datetime, event
1, 2015-01-1 13:30, start
2, 2015-01-1 13:33, start
3, 2015-01-1 13:38, start
2, 2015-01-1 13:57, end
1, 2015-01-1 14:03, end
1, 2015-01-1 14:07, start
1, 2015-01-1 14:12, end

我希望像这样检索它们:

person, start, end
1, 2015-01-01 13:30, 2015-01-01 14:03
1, 2015-01-01 14:07, 2015-01-01 14:12
2, 2015-01-01 13:33, 2015-01-01 13:57
3, 2015-01-01 13:38, null

我似乎无法将关键字放在一起来找到这种“组合行”机制或类似的场景。

最佳答案

没有子查询

SELECT startevent.person_id as person, 
startevent.datetime as [start],
min(endevent.datetime) as [end]
FROM person_events as startevent
join person_events as endevent
on startevent.person_id = endevent.person_id
and startevent.event = 'start'
and endevent.event = 'end'
and startevent.datetime < endevent.datetime
GROUP BY startevent.person_id, startevent.datetime
ORDER BY startevent.person_id, startevent.datetime

关于mysql - T-SQL 分组/合并记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28770560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com