Mysql 通过不显示具有空值的行来查询总和和分组

Mysql Query sum and group by not showing a row with null values

我有这个查询:

SELECT Customer, SUM(SoldUnits) AS SoldUnits
FROM Uploads
WHERE Year = 2021
AND Week = 11
GROUP BY Customer;

还有Returns我:

Customer SoldUnits
CUSTOMER A 55
CUSTOMER B 32
CUSTOMER D 17

CUSTOMER C 存在,但它没有 week 11 的数据,我想用 0 SoldUnits 显示 CUSTOMER C。我该怎么做?

假设您的 table 确实包含您希望在报告中显示的所有客户,您可以进行条件求和并删除 WHERE 子句:

SELECT Customer,
       SUM(CASE WHEN Year = 2021 AND Week = 11
                THEN SoldUnits ELSE 0 END) AS SoldUnits
FROM Uploads
GROUP BY Customer;