T-SQL组/组合记录

时间:2015-02-27 17:09:16

标签: mysql sql tsql group-by

我有一个活动表,它包含'start'和(以及其他许多)'end'事件。

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

我似乎无法将关键字组合在一起以找到这种“按行组合”机制或类似方案。

2 个答案:

答案 0 :(得分:1)

没有子查询

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

答案 1 :(得分:0)

对不起,解决方案非常简单......我过于复杂了!

SELECT
    startevent.person_id as person,
    startevent.datetime as [start],
    (
        SELECT TOP 1
            endevent.datetime as [end]
        FROM
            person_events as endevent
        WHERE
            endevent.event = 'end'
        AND
            endevent.datetime >= startevent.datetime
        ORDER BY
            endevent.person_id,
            endevent.datetime
    ) as [end]
FROM
    person_events as startevent
WHERE
    event = 'start'
ORDER BY
    startevent.person_id,
    startevent.datetime