如何删除表sql中的空值

时间:2014-08-19 11:36:54

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

我有一个表(TestTable)如下

PK  |  COL1  |  COL2  |  COL3  |  COL4  |  COL5
1   |  1     |  NULL  |  NULL  |  NULL  |  NULL
2   |  NULL  |  43    |  1.5   |  7.8   |  NULL
3   |  NULL  |  NULL  |  NULL  |  NULL  |  1
4   |  1     |  NULL  |  NULL  |  NULL  |  NULL
5   |  NULL  |  48    |  10.5  |  17.8  |  NULL
6   |  NULL  |  NULL  |  NULL  |  NULL  |  1

我想得到如下结果

PK  |  COL1  |  COL2  |  COL3  |  COL4  |  COL5
1   |  1     |  43    |  1.5   |  7.8   |  1
2   |  1     |  48    |  10.5  |  17.8  |  1

我试过以下

Select 
[COL1],
[COL2],
[COL3],
[COL4],
 (select top 1 
[COL5]  from  TestTable
where [COL5] is not null and PK <= t1.pk
order by PK DESC) as [COL5]
FROM TestTable as t1 
Where 
[COL1] IS NOT NULL AND
[COL2] IS NOT NULL AND
[COL3] IS NOT NULL AND
[COL4] IS NOT NULL 

该脚本有效,但我得到空结果集。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

看起来你在col1中有一个值后跟一组行,这些行应该合并为一行,直到col1中的下一个值。

如果是这样,您可以通过为每行分配一个计数 - 行中或之前col1中的非空值的数量来执行此操作。然后可以将其用于聚合。

您没有提及数据库,因此我将使用相关子查询来执行此操作:

select row_number() over (order by max(pk)) as pk,
       max(col1) as col1,
       max(col2) as col2,
       max(col3) as col3,
       max(col4) as col4,
       max(col5) as col5
from (select t.*,
             (select count(t2.col1)
              from testtable t2
              where t2.pk <= t.pk
             ) as grpid
      from testtable t
     ) t
group by grpid;

答案 1 :(得分:0)

你在TestTable中没有任何行

[COL1] IS NOT NULL AND
[COL2] IS NOT NULL AND
[COL3] IS NOT NULL AND
[COL4] IS NOT NULL