透视 SQL 结果

Pivot SQL results

我有一个 table 叫测试:

创建table测试 (时间整数, 事件 varchar(50));

INSERT INTO [dbo].[test]
       ([time]
       ,[event])
 VALUES
       (8,'start'),
       (9,'stop'),
       (11,'start'),
       (12,'stop'),
       (null,'start')

    select No , sum(case when event ='start' then time end) start,
    sum(case when event ='stop' then time end) stop
    From
    (select ROW_NUMBER()OVER( partition by event order by time)No,time,event
    from 
    (select isnull(time,0)as time, event from [dbo].[test] )y
     )x
    group by No

如何让空值在最后而不是开头的正确位置排序,是否有更好的方法来编写此查询?

The expected outcome 
 Row No  Start Stop
  1      8     9
  2      11    12
  3      Null  

您可以使用 case 将空值移动到最后。

试试这个:

select No,
    sum(case when event = 'start' then time end) start,
    sum(case when event = 'stop' then time end) stop
from (
    select ROW_NUMBER() over (
            partition by event order by case when time is null then 1 else 0 end,
                time
            ) No,
        time,
        event
    from (
        select time,
            event
        from @test
        ) y
    ) x
group by No

Demo