返回值0或0.00以及where子句MySQL

时间:2017-06-08 02:43:47

标签: mysql database join case

在我调试并查看我的查询测试时,我注意到我的一些结果有 NULL 值。我想返回它们或者根据它们的类型将它们看作0或0.00的值,就像高级一样。

我用case语句尝试了它,但它没有得到我想要的结果为0。

这是根据类型的where子句确定的。

这是我的疑问:

SELECT a.ID as EMPLOYEE, a.DOB as Date, a.AMOUNT as DECLARED, 
(SELECT (CASE WHEN 

SUM(gndsale.AMOUNT) and gndsale.ID IS NULL then "0" and gndsale.typeid = "10" else 
SUM(gndsale.AMOUNT) END) 
from gndsale where gndsale.ID= b.ID and 
gndsale.typeid = "10" and gndsale.DOB = a.DOB)  as `SENIOR 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 DECLARED order by STR_TO_DATE(a.DOB, '%m/%d/%Y')

这是我的结果:

enter image description here

我想将Null Value设为0

2 个答案:

答案 0 :(得分:1)

一种方法是用COALESCE()包装子查询,并使用零作为默认值:

SELECT
    a.ID AS EMPLOYEE,
    a.DOB AS Date,
    a.AMOUNT AS DECLARED, 
    COALESCE(
        (SELECT
            CASE WHEN SUM(gndsale.AMOUNT) AND gndsale.ID IS NULL AND gndsale.typeid = "10"
                 THEN 0 ELSE SUM(gndsale.AMOUNT) END
        FROM gndsale
        WHERE gndsale.ID = b.ID AND
              gndsale.typeid = "10" AND
              gndsale.DOB = a.DOB), 0) AS `SENIOR 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 DECLARED
ORDER BY STR_TO_DATE(a.DOB, '%m/%d/%Y')

答案 1 :(得分:0)

试试这个:

select EMPLOYEE,`Date`,DECLARED,case when SENIOR_DISCOUNT is null then 0 else SENIOR_DISCOUNT end as `SENIOR DISCOUNT` from
(SELECT a.ID as EMPLOYEE, a.DOB as Date, a.AMOUNT as DECLARED, 
(SELECT (CASE WHEN 

SUM(gndsale.AMOUNT) and gndsale.ID IS NULL then "0" and gndsale.typeid = "10" else 
SUM(gndsale.AMOUNT) END) 
from gndsale where gndsale.ID= b.ID and 
gndsale.typeid = "10" and gndsale.DOB = a.DOB)  as `SENIOR_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 DECLARED order by STR_TO_DATE(a.DOB, '%m/%d/%Y')) as a