如何忽略t-sql函数中的空值?

时间:2018-05-31 17:20:21

标签: sql-server tsql

我在两个市场数据表之间进行外连接。这两个表的交易量报告不同,因此我需要单独查询它们然后对结果求和。

问题是第二个查询是针对不经常发生的交易条件,因此有时不返回任何结果。所以c.volume有值,md.volume为null,因为加法结果我得到null。

如何将null视为0?

select 
    c.the_time, c.symbol, c.volume + md.volume 
from 
    -- These are single shares
    (select 
         (time_stamp / 100000) as the_time, symbol, 
         sum(size) as volume 
     from 
         [20160510]
     where 
         price_field = 0
         and (size > 0
         and tradecond != 0)
     group by 
         (time_stamp / 100000), symbol) as c
full outer join 
    (select 
         d.the_time, d.symbol, d.volume as volume 
     from 
         -- These are single shares when multiplied by -1
        (select 
             (time_stamp / 100000) as the_time, symbol, sum(size) * -1 as volume 
         from 
             [20160510]
         where 
             price_field = 0
             and size < 0
         group by 
             (time_stamp / 100000), symbol) as d) as md on md.the_time = c.the_time 
                                                        and md.symbol = c.symbol

1 个答案:

答案 0 :(得分:3)

你应该考虑使用COALESCE。 请注意,您也可以使用ISNULL,但COALESCE是ANSI标准功能。请参阅 reference link

使用COALESCE后的查询将类似于

select 
    c.the_time, c.symbol, COALESCE(c.volume,0) + COALESCE(md.volume ,0)
from 
    -- These are single shares
    (select 
         (time_stamp / 100000) as the_time, symbol, 
         sum(size) as volume 
     from 
         [20160510]
     where 
         price_field = 0
         and (size > 0
         and tradecond != 0)
     group by 
         (time_stamp / 100000), symbol) as c
full outer join 
    (select 
         d.the_time, d.symbol, d.volume as volume 
     from 
         -- These are single shares when multiplied by -1
        (select 
             (time_stamp / 100000) as the_time, symbol, sum(size) * -1 as volume 
         from 
             [20160510]
         where 
             price_field = 0
             and size < 0
         group by 
             (time_stamp / 100000), symbol) as d) as md on md.the_time = c.the_time 
                                                        and md.symbol = c.symbol