TSQL选择列的不同值,但显示具有最少NULL值的行

时间:2018-06-28 11:13:10

标签: tsql distinct-values

我有以下几列

COL1 COL2   COL3    COL4
1    2      NULL    Value1
1    NULL   NULL    Value1
1    NULL   NULL    Value2
1    3      NULL    Value2

The result set I want is 

COL1    COL2    COL3    COL4
1        2      NULL    Value1
1        3      NULL    Value2

这样做的逻辑是,如果在COL 4中存在一个不同的值,则应显示该值,但是每个不同的值只能显示一行。 要显示的一行应具有该唯一值的任何行中具有最少NULL值的列

对此稍作停留,将不胜感激。

1 个答案:

答案 0 :(得分:1)

假设您将此应用到合理的静态表中,则可以应用按每个row_number值分组的Col4,并按不是null的其他列的数量进行排序:

declare @t table(Col1 int,Col2 int,Col3 int,Col4 nvarchar(6));
insert into @t values
 (1,2   ,NULL,'Value1')
,(1,NULL,NULL,'Value1')
,(1,NULL,NULL,'Value2')
,(1,3   ,NULL,'Value2')
;

with d as
(
    select Col1
            ,Col2
            ,Col3
            ,Col4
            ,row_number() over (partition by Col4
                                order by case when Col1 is null then 1 else 0 end
                                        +case when Col2 is null then 1 else 0 end
                                        +case when Col3 is null then 1 else 0 end
                               ) as rn
    from @t
)
select Col1
        ,Col2
        ,Col3
        ,Col4
from d
where rn = 1
;

输出:

+------+------+------+--------+
| Col1 | Col2 | Col3 |  Col4  |
+------+------+------+--------+
|    1 |    2 | NULL | Value1 |
|    1 |    3 | NULL | Value2 |
+------+------+------+--------+
相关问题