SQL union all不包含零值

时间:2012-09-20 09:44:39

标签: sql sql-server zero union-all

我使用union all来统一多个查询,但是union all并没有为这些零值插入空行。我在网站上看了一下,根据这个问题,它应该包含它们:

mysql union with NULL fields

这些是我的疑问:

select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 1 and SMTH > 0 )  
union all
select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 2 and SMTH > 0 )  
union all
select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 3 and SMTH > 0 )  
union all
select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 4 and SMTH > 0 )  

结果:

10068
3967
895

四个独立查询:

select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 1 and SMTH > 0 )  

select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 2 and SMTH > 0 )  

select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 3 and SMTH > 0 )  

select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 4 and SMTH > 0 )   

结果:

10068
3967
0
895

所以基本上因为我认为上一个问题的答案是正确的,我做错了什么?。

谢谢!

2 个答案:

答案 0 :(得分:2)

哪一列为空? 您确定,由于您的where子句,空值不会被删除吗? 请记住,使用null的操作始终为null(除了使用IS NULL进行测试)。

答案 1 :(得分:0)

第三个查询返回0.为什么你认为是null?这种查询的任何方式都比union

更清晰

如果表中有主键(此查询中为id):

select SMTH, Data, [date]
from 
    H.D.T
    inner join (
        select id, Data, max([date]) as [date]
        from H.D.T
        where Data in (1, 2, 3, 4) and SMTH > 0
        group by id, Data
    ) s on s.id = H.D.T.id
order by Data