透视SQL结果

时间:2017-02-28 20:42:58

标签: sql null numbers pivot row

我有一个名为test的表:

创建表测试  (时间int,   event 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

如何获取null值以在最终而不是开头的正确位置排序,是否有更好的方法来编写此查询?

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

1 个答案:

答案 0 :(得分:0)

您可以使用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