如何删除空值并从表中的值中获取行

时间:2014-11-22 14:10:25

标签: sql

请帮我完成下面的任务。我有一个有四列的表a col1,col2,col3和col4。我想从这些列中检索,删除空值。

所以,如果我的桌子有

col1 | col2 | col3 | col4
-----+------+------+-----
A    | B    |  NULL| NULL
C    | D    |  NULL| NULL
NULL | NULL |  E   | F
NULL | NULL |  G   | H

我希望结果是

col1 | col2 | col3 | col4
-----+------+------+-----
A    | B    | E    | F  
C    | D    | G    | H  

1 个答案:

答案 0 :(得分:0)

这是一个解决方案。我使用了解析ROW_NUMBER()来合成用于连接行的键。连接是完全外部的,以便满足空值和值的不等分配。

with cte as (select * from t23)
   , a as ( select col1, row_number() over (order by col1) as rn
            from cte
            where col1 is not null )
   , b as ( select col2, row_number() over (order by col2) as rn
            from cte
            where col2 is not null )            
   , c as ( select col3, row_number() over (order by col3) as rn
            from cte
            where col3 is not null )            
   , d as ( select col4, row_number() over (order by col4) as rn
            from cte
            where col4 is not null )            
select a.col1
       , b.col2
       , c.col3
       , d.col4
from a
     full outer join b
          on a.rn = b.rn
     full outer join c
          on a.rn = c.rn
     full outer join d
          on a.rn = d.rn
/

SQL Fiddle is for Oracle,但此解决方案适用于支持排名分析功能的任何数据库。公用表表达式是可选的,它只是使其他子查询更容易编写。