mysql sum其中sum结果为Null

时间:2015-04-28 18:40:27

标签: mysql

我正在使用以下查询,如果sum(otb.special_discount)的结果不为空,则该查询正常工作。但如果结果为null,则sum查询的整个结果将返回null。

我应该如何更正例如sum(otb.total_charges)的查询为10000且sum(otb.special_discount)为空,我希望结果为10000。

SELECT ott.test_name, (sum(otb.total_charges)- sum(otb.special_discount))as test_charges,
count(otb.id)count
from opd_test_bill otb,opd_test_type ott where otb.bill_type='p'
and otb.test_name=ott.id 
and date between '2015-04-26 16:00:59' and '2015-04-27 06:00:00' 
group by ott.test_name

2 个答案:

答案 0 :(得分:1)

快速解决方案:

SELECT ott.test_name, (COALESCE(sum(otb.total_charges),0)- COALESCE(sum(otb.special_discount),0))as test_charges,
count(otb.id)count
from opd_test_bill otb,opd_test_type ott where otb.bill_type='p'
and otb.test_name=ott.id 
and date between '2015-04-26 16:00:59' and '2015-04-27 06:00:00' 
group by ott.test_name

https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce

返回列表中的第一个非NULL值,如果没有非NULL值,则返回NULL。

您也可以使用' IFNULL':

https://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull

SELECT ott.test_name, (IFNULL(sum(otb.total_charges),0)- IFNULL(sum(otb.special_discount),0))as test_charges,
count(otb.id)count
from opd_test_bill otb,opd_test_type ott where otb.bill_type='p'
and otb.test_name=ott.id 
and date between '2015-04-26 16:00:59' and '2015-04-27 06:00:00' 
group by ott.test_name

答案 1 :(得分:0)

使用COALESCE功能:

     SELECT ott.test_name, 
     (sum(otb.total_charges)- COALESCE(sum(otb.special_discount),0))as test_charges,
     count(otb.id)count
     from opd_test_bill otb join opd_test_type ott 
     on otb.test_name=ott.id     
     where otb.bill_type='p'and date between '2015-04-26 16:00:59' and '2015-04-27 06:00:00' 
      group by ott.test_name