即使没有行也显示0

时间:2017-07-18 08:04:10

标签: sql postgresql

我创建了这个查询

SELECT 
    CASE 
        WHEN (c.designation <> '') THEN UPPER(c.designation) 
        ELSE 'CATEGORIE INCONNU' 
    END AS designation,
    CASE 
        WHEN COUNT(lg) > 0  THEN SUM (lg.montant_categorie_maintenance) 
        ELSE 0 
    END AS valeur
FROM sch_gparc.maint_categorie_maintenance c 
LEFT JOIN sch_gparc.maint_lg_categorie_maintenance lg
    ON lg.id_categorie = c.id
LEFT JOIN sch_gparc.maint_maintenance m
    ON lg.id_maintenance = m.id 
WHERE EXTRACT( MONTH FROM m.date_fin::DATE) = EXTRACT( MONTH FROM '01/04/2017'::DATE)
    AND EXTRACT( YEAR FROM m.date_fin::DATE) = EXTRACT( YEAR FROM '01/04/2017'::DATE)
    AND m.type_maintenance = 'PREVENTIVE'
GROUP BY c.designation 

此查询的目标是显示所有c.designation,如果没有记录显示0

问题是:它没有显示任何内容(当我执行左连接时没有记录的情况)。

编辑:所需数据

| designation    |   value       |
|    MOTEUR      |     0         |
|    DIVERS      |     0         |

现在展示什么:没有。

2 个答案:

答案 0 :(得分:0)

“问题”是,当您进行分组时,您将丢失没有任何内容可分组的行。

我通常只是将聚合查询加入到我第一次选择的表中。

SELECT
    s.designation,
    COALESCE(s.valeur, 0) -- coalesce the NULL rows to zero
FROM sch_gparc.maint_categorie_maintenance cat
LEFT JOIN (
    SELECT
        c.id,
        CASE
            WHEN (c.designation <> '') THEN UPPER(c.designation)
            ELSE 'CATEGORIE INCONNU'
        END AS designation,
        SUM (lg.montant_categorie_maintenance) AS valeur
    FROM sch_gparc.maint_categorie_maintenance c
    LEFT JOIN sch_gparc.maint_lg_categorie_maintenance lg
        ON lg.id_categorie = c.id
    LEFT JOIN sch_gparc.maint_maintenance m
        ON (
            lg.id_maintenance = m.id
            AND EXTRACT( MONTH FROM m.date_fin::DATE) = EXTRACT( MONTH FROM '01/04/2017'::DATE)
            AND EXTRACT( YEAR FROM m.date_fin::DATE) = EXTRACT( YEAR FROM '01/04/2017'::DATE)
            AND m.type_maintenance = 'PREVENTIVE'
        )
    GROUP BY c.designation
) s ON (s.id = cat.id)

答案 1 :(得分:0)

我尝试了下面的一个,它正在运行:

select c.designation , coalesce(gm.valeur,0) as valeur  
from sch_gparc.maint_categorie_maintenance c 
left join (SELECT 
    CASE 
        WHEN (c.designation <> '') THEN UPPER(c.designation) 
        ELSE 'CATEGORIE INCONNU' 
    END AS designation,
    CASE 
        WHEN COUNT(m.id) > 0  THEN SUM (lg.montant_categorie_maintenance) 
        ELSE 0 
    END AS valeur
FROM sch_gparc.maint_categorie_maintenance c 
LEFT JOIN sch_gparc.maint_lg_categorie_maintenance lg
    ON lg.id_categorie = c.id
LEFT JOIN sch_gparc.maint_maintenance m
    ON lg.id_maintenance = m.id 

WHERE 
(EXTRACT( MONTH FROM m.date_fin::DATE) = EXTRACT( MONTH FROM '01/05/2017'::DATE)
    AND EXTRACT( YEAR FROM m.date_fin::DATE) = EXTRACT( YEAR FROM '01/05/2017'::DATE)
    AND m.type_maintenance = 'PREVENTIVE') or m.id is null
GROUP BY 1)gm on gm.designation = UPPER(c.designation)

希望能帮到你。