删除数据透视查询中的空值

时间:2018-03-07 09:20:09

标签: sql sql-server tsql

这个似乎就像一个直截了当的场景,但我很难过......

我有一张包含以下数据的表格:

IsGood  Reason
------  ------
1       Good One
1       Good Two
0       Bad One
0       Bad Two
0       Bad Three

我想查询它以水平方式转动数据,如下所示:

GoodReason  BadReason
----------  ---------
Good One    Bad One
Good Two    Bad Three
NULL        Bad Two

然而,结果如下:

GoodReason  BadReason
----------  ---------
NULL        Bad One
NULL        Bad Three
NULL        Bad Two
Good One    NULL
Good Two    NULL    
create table #reasons
(
    IsGood bit,
    Reason nvarchar(20)
)
insert into #reasons 
           ( IsGood,   Reason      )
    values ( 1,        'Good One'  )
         , ( 1,        'Good Two'  )
         , ( 0,        'Bad One'   )
         , ( 0,        'Bad Two'   )
         , ( 0,        'Bad Three' )

select * from #reasons

select 'Attempt #1'
    , case when r.IsGood = 1 then r.Reason else null end GoodReason
    , case when r.IsGood = 0 then r.Reason else null end BadReason
from
    #reasons r
group by r.IsGood, r.Reason

select 'Attempt #2'
    , max(case when r.IsGood = 1 then r.Reason else null end) GoodReason
    , max(case when r.IsGood = 0 then r.Reason else null end) BadReason
from
    #reasons r
group by r.IsGood, r.Reason

drop table #reasons
go

好/坏的原因是由用户界面推动的,可以改变,加入等,所以我排除了PIVOT方法 - 很高兴接受教育!。

Repo也可在 - http://sqlfiddle.com/#!18/9ebc3/2

获取

如何在没有空值的情况下获得结果?

非常感谢,

弗朗兹。

1 个答案:

答案 0 :(得分:2)

使用ROW_NUMBER()函数根据 IsGood 生成序列号,并在GROUP BY子句中使用派生表

select 
      max(case when IsGood = 1 then Reason end) GoodReason,
      max(case when IsGood = 0 then Reason end) BadReason 
from
(
    select *, 
           row_number() over (partition by IsGood order by IsGood) Seq
    from reasons
)a
group by Seq