如果计算中存在null,则返回原始值

时间:2017-06-08 09:19:48

标签: mysql database join coalesce

如果我的查询只计算原始值,如果它从另一个类型计算空值,那么我遇到了问题。我正在根据类型5减去typeid 10来计算这些原始值。

请注意我的数据结构和我的数据类型都在各处,并且很难为新用户阅读。为了确定值,您必须关注type和typeid。

我获得折扣原始价值的类型是5

以下是查询和原始值:

查询:

select a.ID as `ID`, a.DOB as `DATE`, a.AMOUNT as `TOTAL`, (SELECT 
coalesce(sum(case when gndsale.type= "5" then gndsale.amount end), 0) from 
gndsale where gndsale.ID = b.ID and gndsale.DOB = a.DOB having 
sum(gndsale.type = "5") > 0 ) as `DISCOUNTS` FROM gndsale a 
INNER JOIN emp b ON a.ID = b.ID  
WHERE a.type = "22" and STR_TO_DATE(a.DOB, '%m/%d/%Y') BETWEEN '2017-05-01' 
AND '2017-05-31' GROUP BY TOTAL order by STR_TO_DATE(a.DOB, '%m/%d/%Y')

我的 typeid为10 将确定另一个高级

的折扣

以下是查询和高级

的值

查询:

select a.ID as `ID`, a.DOB as `DATE`, a.AMOUNT as `TOTAL`, (SELECT 
coalesce(sum(case when gndsale.typeid= "10" then gndsale.amount end), 0) from 
gndsale where gndsale.ID= b.ID and gndsale.DOB = a.DOB having 
sum(gndsale.typeid = "10") > 0 ) as `DISCOUNTS` FROM gndsale a 
INNER JOIN emp b ON a.ID= b.ID  
WHERE a.type = "22" and STR_TO_DATE(a.DOB, '%m/%d/%Y') BETWEEN '2017-05-01' 
AND '2017-05-31' GROUP BY TOTAL order by STR_TO_DATE(a.DOB, '%m/%d/%Y')

我的高级折扣有空值。

我想要做的是我想减去原始折扣价值和高级折扣价值,这意味着我必须减去 type = 5和typeid = 10 的值。幸运的是,我能够计算并得到了我的结果

这里是问题我的预期结果是空值。问题是因为它从高级结果计算一个空值我想要的是如果空值的计算空值,那么空值应仅返回原始折扣值。

这是我的疑问:

select a.ID as `ID`, a.DOB as `DATE`, a.AMOUNT as `TOTAL`, (SELECT 
coalesce(sum(case when gndsale.type= "5" then gndsale.amount end), 0) - 
coalesce(sum(case when gndsale.TYPEID= "10" then gndsale.amount end), 0) END 
from gndsale where gndsale.ID= b.ID and gndsale.DOB = a.DOB having 
sum(gndsale.type = "5") > 0 and sum(gndsale.TYPEID= "10") > 0 ) as `OTHER 
DISCOUNT` FROM gndsale a INNER JOIN emp b ON a.ID= b.ID WHERE a.type 
= "22" and STR_TO_DATE(a.DOB, '%m/%d/%Y') BETWEEN '2017-05-01' AND '2017-05-
31' GROUP BY TOTAL order by STR_TO_DATE(a.DOB, '%m/%d/%Y')

注意:他们是基于日期的我还不能发布图片..我目前的结果是其他折扣。

0 个答案:

没有答案