当多列数据在某些列中为空时,如何在单行中获取数据?

时间:2018-01-27 10:19:05

标签: sql sql-server sql-server-2012 sql-server-2008-r2

当多列数据在某些列中为空时,如何在单行中获取数据? 以下是方案

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

3 个答案:

答案 0 :(得分:3)

您可以使用如下聚合函数:

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 

但在这种情况下,MinMax或更有意义,而不是AvgSum

答案 1 :(得分:1)

select max(col1) as col1, 
       max(col2) as col2, 
       max(col3) as col3, 
       max(col4) as col4
from your_table

答案 2 :(得分:0)

试试这种方式。

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