如何将日期时间值从行转换为列

问题描述 投票:0回答:1
Starttime                   Shift
--------------------------------------------
2019-11-21 10:36:11.393      1 
2019-11-21 10:38:22.590      1
2019-11-21 10:40:32.940      1
2019-11-21 10:36:11.393      2
2019-11-21 10:38:45.407      2

我需要结果

Shift     Starttime1               starttime2                 starttime3
-----------------------------------------------------------------------
1       2019-11-21 10:36:11.393    2019-11-21 10:38:22.590  2019-11-21 10:40:32.940 
2       2019-11-21 10:36:11.393    2019-11-21 10:38:45.407
sql sql-server ssrs-2012
1个回答
0
投票

您可以使用row_number()和聚合:

select 
    shift,
    max(case when rn = 1 then starttime end) starttime1,
    max(case when rn = 2 then starttime end) starttime2,
    max(case when rn = 3 then starttime end) starttime3
from (
    select t.*, row_number() over(partition by shift order by starttime) rn
    from mytable t
) t
group by shift
© www.soinside.com 2019 - 2024. All rights reserved.