TSQL 选择列非重复值,但显示 NULL 值量最少的行



>我有以下列

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 值列

有点卡在这个上面,任何帮助将不胜感激。

假设您将其应用于合理的静态表,您可以应用按每个Col4值分组的row_number,按未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 |
+------+------+------+--------+

最新更新