SQL服务器:删除多行空值
问题描述:
我有一个表是这样的:SQL服务器:删除多行空值
Result Col1 Col2 Col3
-----------------------------
Row1 null 1 null
Row1 2 null null
Row1 null null 3
Row1 1 null null
Row1 null 2 null
Row1 null null 3
,我希望得到的结果类似
Result Col1 Col2 Col3
-----------------------------
Row1 2 1 3
Row1 1 2 3
如何在SQL Server中完成这件事表?我知道如果我使用Col1,Col2,Col3的MAX
,我只会得到一行。但我需要得到两排。
我该怎么做?
答
这很棘手。您可以使用row_number()
为每个值分配一个连续值,然后进行汇总。
您的数据缺乏排序 - SQL表格表示无序集合。假设你有一个排序列,你必须每行只有一个非NULL
值:
select t.result, max(col1) as col1, max(col2) as col2, max(col3) as col3
from (select t.*,
row_number() over (partition by case when col1 is not null then 1
when col2 is not null then 2
when col3 is not null then 3
order by ? -- the ordering column
) as seqnum
from t
) t
group by t.result, seqnum;
如果你能有每行多个非NULL
值,接下来的问题是不明确的。询问另一个问题并提供样本数据和期望的结果。
SQL表格表示无序集合。你如何识别哪些值一起? –