2017-09-22 69 views
-1

我有一個表是這樣的: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,我只會得到一行。但我需要得到兩排。

我該怎麼做?

+3

SQL表格表示無序集合。你如何識別哪些值一起? –

回答

1

這很棘手。您可以使用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值,接下來的問題是不明確的。詢問另一個問題並提供樣本數據和期望的結果。