如何从表中选择以下格式的记录?

时间:2018-06-05 12:48:58

标签: sql

表:

id  status date
133 start  22/05/2018
133 end    22/05/2018
133 start  23/05/2018
133 end    23/05/2018

我希望查询显示这样的记录。

id  intime      outtime
133 22/05/2018  22/05/2018
133 23/05/2018  23/05/2018

1 个答案:

答案 0 :(得分:0)

您可以使用row_number()并进行汇总:

select id, max(case when status = 'start' then date end) as intime,
           max(case when status = 'end' then date end) as outtime
from (select *, row_number() over (partition by status order by date) as seq
      from table
     ) t
 group by id, seq;

您尚未标记任何DBMS,但大部分DBMS都具有分析功能。