如何使用两个表格制作单个视图

时间:2017-07-10 10:54:16

标签: sql postgresql

你好,所以我对这两个问题都很相似,但是现在要把它们联合起来,我会得到垃圾或一些奇怪的乘法。

SELECT ra.agno,cod_ine_reg, SUM(ra.cantidad) AS total_aprehendidos
FROM registra_aprehendidos ra JOIN comuna USING (id_pref)
JOIN provincia USING (cod_ine_prov)
JOIN region USING (cod_ine_reg)
GROUP BY ra.agno, cod_ine_reg;

https://i.imgur.com/TaFHBdo.png

SELECT rd.agno,cod_ine_reg, SUM(rd.cantidad) AS total_denuncias
FROM registra_denuncias rd JOIN comuna USING (id_pref)
JOIN provincia USING (cod_ine_prov)
JOIN region USING (cod_ine_reg)
GROUP BY rd.agno, cod_ine_reg;

https://i.imgur.com/dyRe0WF.png

基本上我不能这样做,有关如何做的任何想法?我尝试过使用unite,联合所有和一些变种而没有结果。

https://i.imgur.com/0WXieY5.png

1 个答案:

答案 0 :(得分:1)

应该像这样工作:

SELECT   apre.agno
        ,apre.cod_ine_reg
        ,apre.total_aprehendidos
        ,denu.total_denuncias
  FROM  (    
            SELECT ra.agno,cod_ine_reg, SUM(ra.cantidad) AS total_aprehendidos
            FROM registra_aprehendidos ra JOIN comuna USING (id_pref)
            JOIN provincia USING (cod_ine_prov)
            JOIN region USING (cod_ine_reg)
            GROUP BY ra.agno, cod_ine_reg     
         ) apre
LEFT OUTER JOIN
        (
            SELECT rd.agno,cod_ine_reg, SUM(rd.cantidad) AS total_denuncias
            FROM registra_denuncias rd JOIN comuna USING (id_pref)
            JOIN provincia USING (cod_ine_prov)
            JOIN region USING (cod_ine_reg)
            GROUP BY rd.agno, cod_ine_reg
        ) denu
     ON apre.agno = denu.agno
    AND apre.cod_ine_reg = denu.cod_ine_reg     

如果你期望来自registra_denuncias的结果,而没有匹配registra_aprehendidos中的记录,那么FULL JOIN将是更好的方法,如:

SELECT   COALESCE(apre.agno, denu.agno) as agno
        ,COALESCE(apre.cod_ine_reg, denu.cod_ine_reg) as cod_ine_reg
        ,COALESCE(apre.total_aprehendidos,0) as total_aprehendidos
        ,COALESCE(denu.total_denuncias,0) as total_denuncias
  FROM  (    
            SELECT ra.agno,cod_ine_reg, SUM(ra.cantidad) AS total_aprehendidos
            FROM registra_aprehendidos ra JOIN comuna USING (id_pref)
            JOIN provincia USING (cod_ine_prov)
            JOIN region USING (cod_ine_reg)
            GROUP BY ra.agno, cod_ine_reg     
         ) apre
FULL OUTER JOIN
        (
            SELECT rd.agno,cod_ine_reg, SUM(rd.cantidad) AS total_denuncias
            FROM registra_denuncias rd JOIN comuna USING (id_pref)
            JOIN provincia USING (cod_ine_prov)
            JOIN region USING (cod_ine_reg)
            GROUP BY rd.agno, cod_ine_reg
        ) denu
     ON apre.agno = denu.agno
    AND apre.cod_ine_reg = denu.cod_ine_reg