在SQL中将列与空值组合在一起

时间:2014-10-07 10:52:59

标签: mysql sql

我有SQL查询,可以获取这样的结果

Column1 Column2     Column3 Column4    Column5 Column6 Coulmn7
A-66001 46063       137039  0-82-A0-A0 NULL   NULL     NULL
A-66001 46063       139045  NULL       NULL   NULL     NULL
A-66001 46063       141051  NULL       40     NULL     30
A-66001 46063       237164  NULL    NULL      20       NULL

我想要一个结合所有行的结果。

Column1 Column2     Column3 Column4    Column5 Column6 Coulmn7
A-66001 46063       137039  0-82-A0-A0 40        20     30 

我尝试使用Max功能,但这对字符串不起作用。最早需要解决方案

2 个答案:

答案 0 :(得分:2)

使用max()

select column1, column2, min(column3) as column3,
       max(column4) as column4, 
       max(column5) as column5, 
       max(column6) as column6, 
       max(column7) as column7 
from table t
group by column1, column2;

我猜你想要真正按前两列分组,Column3的任意值都是合适的。

答案 1 :(得分:0)

尝试以下:

select
(select column1 from table where column1 is not null limit 1) as column1
(select column2 from table where column2 is not null limit 1) as column2
(select column3 from table where column3 is not null limit 1) as column3
(select column4 from table where column4 is not null limit 1) as column4
(select max(cast(column5 as int)) from table where column5 is not null limit 1) as column5
(select max(cast(column6 as int)) from table where column6 is not null limit 1) as column6
(select max(cast(column7 as int)) from table where column7 is not null limit 1) as column7

from table