【问题标题】:How can I get data in single row when multiple columns data have null in some columns?当多列数据在某些列中为空时,如何获取单行数据?
【发布时间】:2018-01-27 10:19:05
【问题描述】:
当多列数据在某些列中为空时,如何获取单行数据?
以下是场景
col1 col2 col3 col4
----- ------ ---------------
1 NULL NULL NULL
NULL 2 NULL NULL
NULL NULL 3 NULL
NULL NULL NULL 4
I want output like this
col1 col2 col3 col4
----- ------ ---------------
1 2 3 4
【问题讨论】:
标签:
sql
sql-server
sql-server-2012
sql-server-2008-r2
【解决方案1】:
您可以使用如下聚合函数:
select min(col1) as col1,min(col2) as col2,min(col3) as col3,min(col4) as col4 from t
select max(col1) as col1,max(col2) as col2,max(col3) as col3,max(col4) as col4 from t
select sum(col1) as col1,sum(col2) as col2,sum(col3) as col3,sum(col4) as col4 from t
select avg(col1) as col1,avg(col2) as col2,avg(col3) as col3,avg(col4) as col4 from t
但是在这种情况下,Min 或 Max 或比 Avg 和 Sum 更有意义。
【解决方案2】:
select max(col1) as col1,
max(col2) as col2,
max(col3) as col3,
max(col4) as col4
from your_table
【解决方案3】:
试试这个方法。
SELECT DISTINCT
(SELECT TOP 1 Col1 FROM TestTable WHERE Col1 IS NOT NULL) AS 'Column1',
(SELECT TOP 1 Col2 FROM TestTable WHERE Col2 IS NOT NULL) AS 'Column2',
(SELECT TOP 1 Col3 FROM TestTable WHERE Col3 IS NOT NULL) AS 'Column3',
(SELECT TOP 1 Col4 FROM TestTable WHERE Col4 IS NOT NULL) AS 'Column4'
From TestTable
示例 01
Col1 Col2 Col3 Col4
----- ------ ---------------
1 NULL NULL NULL
NULL 2 NULL NULL
NULL NULL 3 NULL
NULL NULL NULL 4
结果
Column1 Column2 Column3 Column4
-------------------------------
1 2 3 4
示例 02
Col1 Col2 Col3 Col4
----- ------ ---------------
1 NULL NULL NULL
NULL 2 NULL 2
5 NULL 3 NULL
NULL NULL NULL 4
结果
Column1 Column2 Column3 Column4
-------------------------------
1 2 3 2