我正在搜索某些表,我想计算表的结果,当它在我设置的日期没有数据时,我想显示数字零。
SELECT
l.key as "Licença",
coalesce(sum(c."customersAmount"), 0) as "Comsumo dos ultimos 30 dias"
FROM
consumptions c
LEFT JOIN licenses l on c."licenseKey"=l.key
WHERE
c."consumedAt" >= current_date - interval '30' day AND
l.label LIKE '%Casa%'
GROUP BY
l.key
ORDER BY
l.key ASC;
没有消耗的lkey,我想显示数字零(0)。
我该怎么做? 谢谢
答案 0 :(得分:0)
您可以使用
CASE WHEN l.key NULL THEN 'Empty' ELSE l.key END as "Licença"
或
coalesce(l.key, 'Empty') AS "Licença"
答案 1 :(得分:0)
您应将c."consumedAt" >= current_date - interval '30' day
从WHERE
移到ON
子句。在WHERE
中,它过滤掉所有的行,其中licenses
中没有行被连接,因为"consumedAt"
的行从不为空,并且永远不会大于或等于任何其他值。
SELECT l.key "Licença",
coalesce(sum(c."customersAmount"), 0) "Comsumo dos ultimos 30 dias"
FROM consumptions c
LEFT JOIN licenses l
ON c."licenseKey" = l.key
AND c."consumedAt" >= current_date - interval '30' day
WHERE l.label LIKE '%Casa%'
GROUP BY l.key
ORDER BY l.key ASC;
答案 2 :(得分:0)
我认为您希望licenses
表作为LEFT JOIN
中的第一个表,所以我认为这是您想要的查询:
SELECT l.key as "Licença",
coalesce(sum(c."customersAmount"), 0) as "Comsumo dos ultimos 30 dias"
FROM licenses l LEFT JOIN
consumptions c
ON c."licenseKey" = l.key AND
c."consumedAt" >= current_date - interval '30' day
WHERE l.label LIKE '%Casa%'
GROUP BY l.key
ORDER BY l.key ASC;