T-SQL Start and end date times from a single column

后端 未结 3 1530
夕颜
夕颜 2021-01-24 11:34

I have a single table of on/off events for different assets. I need to get a list of start & stop event times without using a cursor.

Source:

Item          


        
3条回答
  •  天涯浪人
    2021-01-24 11:50

    Untested...

    ;WITH myCTE AS
    (
       SELECT *,
             ROW_NUMBER() OVER (PARTITION BY Item ORDER BY EventDate) AS rn
       FROM MyTable
    )
    SELECT
       M1.Item,
       M1.EventDate AS Start,
       M2.EventDate AS End
    FROM
       myCTE M1
       JOIN
       myCTE M2 ON M1.Item = M2.Item AND M1.rn+1 = M2.rn
    WHERE
       M1.Event = 'On'
       AND
       M2.Event = 'Off';
    

提交回复
热议问题