无数据时显示数字零

时间:2019-04-24 20:58:27

标签: sql postgresql

我正在搜索某些表,我想计算表的结果,当它在我设置的日期没有数据时,我想显示数字零。

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)。

我该怎么做? 谢谢

3 个答案:

答案 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' dayWHERE移到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;