我有一个请求,它会计算不同情况下字段的值。
以下是请求:
tap
如果案件中没有记录,有时我会遇到问题。返回值为null。
我在StackOverflow中看到另一个有趣的问题:
How do I get SUM function in MySQL to return '0' if no values are found?
我尝试将这些函数用于我的请求,但我不明白在我的情况下应用的语法。
有你的想法吗?
谢谢
答案 0 :(得分:2)
只需添加ELSE 0
:
SELECT SUM(CASE WHEN Reliquat_id = 1 THEN Poids ELSE 0 END) AS NbrARRNP,
SUM(CASE WHEN Reliquat_id = 2 THEN Poids ELSE 0 END) AS NbrSTNP,
SUM(CASE WHEN Reliquat_id = 3 THEN Nombre ELSE 0 END) AS NbrARR,
SUM(CASE WHEN Reliquat_id = 4 THEN Nombre ELSE 0 END) AS ST,
SUM(CASE WHEN Reliquat_id = 5 THEN Nombre ELSE 0 END) AS NbrCLASS,
SUM(CASE WHEN Reliquat_id = 6 THEN Nombre ELSE 0 END) AS NbrINDEX
FROM datas
WHERE Chantier_id = 4 AND main_id = 1;
注意:如果没有符合NULL
条件的行,则仍会返回包含所有WHERE
值的行。
答案 1 :(得分:2)
答案 2 :(得分:1)
请试试这个
SELECT IFNULL(SUM(CASE WHEN Reliquat_id = 1 THEN Poids ELSE 0 END),0) AS NbrARRNP,
IFNULL(SUM(CASE WHEN Reliquat_id = 2 THEN Poids ELSE 0 END),0) AS NbrSTNP,
IFNULL(SUM(CASE WHEN Reliquat_id = 3 THEN Nombre ELSE 0 END),0) AS NbrARR,
IFNULL(SUM(CASE WHEN Reliquat_id = 4 THEN Nombre ELSE 0 END),0) AS ST,
IFNULL(SUM(CASE WHEN Reliquat_id = 5 THEN Nombre ELSE 0 END),0) AS NbrCLASS,
IFNULL(SUM(CASE WHEN Reliquat_id = 6 THEN Nombre ELSE 0 END),0) AS NbrINDEX
FROM datas
WHERE Chantier_id = 4 AND main_id = 1;
答案 3 :(得分:0)
对案件使用Else 0(Reliquat_id = 5和Reliquat_id = 6)以及其他情况。请尝试:
SELECT SUM(CASE WHEN Reliquat_id = 1 THEN Poids ELSE 0 END) AS NbrARRNP,
SUM(CASE WHEN Reliquat_id = 2 THEN Poids ELSE 0 END) AS NbrSTNP,
SUM(CASE WHEN Reliquat_id = 3 THEN Nombre ELSE 0 END) AS NbrARR,
SUM(CASE WHEN Reliquat_id = 4 THEN Nombre ELSE 0 END) AS ST,
SUM(CASE WHEN Reliquat_id = 5 THEN Nombre ELSE 0 END) AS NbrCLASS,
SUM(CASE WHEN Reliquat_id = 6 THEN Nombre ELSE 0 END) AS NbrINDEX
from
答案 4 :(得分:0)
最后这是最后一个请求:
SELECT IFNULL(SUM(CASE WHEN Reliquat_id = 1 THEN Poids END),0) AS NbrARRNP,
IFNULL(SUM(CASE WHEN Reliquat_id = 2 THEN Poids END),0) AS NbrSTNP,
IFNULL(SUM(CASE WHEN Reliquat_id = 3 THEN Nombre END),0) AS NbrARR,
IFNULL(SUM(CASE WHEN Reliquat_id = 4 THEN Nombre END),0) AS ST,
IFNULL(SUM(CASE WHEN Reliquat_id = 5 THEN Nombre END),0) AS NbrCLASS,
IFNULL(SUM(CASE WHEN Reliquat_id = 6 THEN Nombre END),0) AS NbrINDEX
FROM datas
WHERE Chantier_id = 4 AND main_id = 1;
我发现这是解决该问题的最佳请求,因为如果数据库中没有记录,“ELSE 0”不起作用并返回0.现在使用IFNULL即使没有记录,它也总是返回0。