我有一个包含许多NULL值的表。因此,我使用COALESCE函数来检索NON NULL值。当COALESCE的结果放在一个列中时,这可以正常工作。但是,我需要将COALESCE的值放在单独的列中,具体取决于它们拾取的位置。
E.g。我有下表。
SELECT COALESCE(Col1, Col2, Col3, Col4) FROM Table 1
会产生: -
Column1
1
1
3
4
但是我不想要那个结果,但我想要这个结果: -
Col1 Col2 Col3 Col4
1 - - -
- 1 - -
- - 3 -
- 4 - -
正如你所看到的,我只想填充一个字段(这就是为什么我起诉COALESCE,但是COALESCE的结果应该如图所示放置,注意每行一个值。
关于如何实现这一结果的任何想法请。
答案 0 :(得分:1)
coalesce can be built with case statements. You need something like the below:
select col1
, case when col1 is not null then null else col2 end 'Col2'
, case when col1 is not null or col2 is not null then null else col3 end 'Col3'
, case when col1 is not null or col2 is not null or col3 is not null then null else col4 end 'Col4'
from table
答案 1 :(得分:0)
You can achieve this with a combination of PIVOT
, UNPIVOT
and ROW_NUMBER
.
declare @t table(rn int identity(1,1) primary key, col1 int, col2 int, col3 int, col4 int);
insert @t values (1,null,null,null), (null,1,0,null), (null,null,3,null), (null,4,null,2);
with a as (
select *, ranking = row_number() over (partition by rn order by col)
from @t a
unpivot ([val] for [col] in ([col1],[col2],[col3],[col4])) p
)
select *
from a
pivot (min(val) for [col] in ([col1],[col2],[col3],[col4])) p
where ranking = 1