T-SQL中全外连接求和时如何将NULL值视为0处理?
解决全外连接后NULL值求和为NULL的问题
这问题太常见了!你碰到的是SQL里NULL值运算的经典陷阱——只要算术运算里包含NULL,结果就会直接变成NULL。好在解决起来很简单,用COALESCE函数把可能为NULL的volume字段替换成0就行。
问题根源
当你执行全外连接时,如果其中一张表没有匹配的行(比如你说的第二个查询场景不常出现、无结果返回),对应的md.volume就会是NULL。而c.volume + md.volume这个运算里,只要有一个值是NULL,整个表达式的结果就会变成NULL,这就是你求和结果不对的原因。
修改后的SQL代码
只需要把原来的求和部分改成用COALESCE包裹可能为NULL的字段,把NULL替换成0:
select c.the_time, c.symbol, COALESCE(c.volume, 0) + COALESCE(md.volume, 0) as total_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 -- These are single shares when multiplied by -1 (select d.the_time, d.symbol, d.volume as volume from (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
关键函数说明
- COALESCE是ANSI标准SQL函数,它会返回传入参数中的第一个非NULL值。比如
COALESCE(md.volume, 0),如果md.volume是NULL就返回0,否则返回md.volume本身。 - 如果你用的是特定数据库,也可以用对应函数:
- MySQL/MariaDB:
IFNULL(md.volume, 0) - Oracle:
NVL(md.volume, 0) - SQL Server:
ISNULL(md.volume, 0)
但COALESCE的兼容性最好,跨数据库都能用。
- MySQL/MariaDB:
这样修改后,不管哪一侧的volume是NULL,都会被当成0来计算,求和结果就不会再是NULL啦!
内容的提问来源于stack exchange,提问作者Behrooz Karjoo
相关产品推荐
相关产品推荐

