当任何一个选择查询未执行或结果为空时,选择查询结果未来?

时间:2015-11-19 06:05:58

标签: postgresql if-statement select join group-by

我已经编写了四个SELECT个查询来获取按napkin type分组的数量。当不能转移或收入数量时,“b”和“c”查询为NULL。所以我们无法获得napkin type

问题是a.napkin_type=b.napkin_type and a.napkin_type=c.napkin_type

WITH a AS (SELECT
             COALESCE(SUM(quantity), 0) AS "receipt",
             napkin_type
           FROM hsc_receipt_entry
           WHERE dvn_cd = '15' AND phc_cd = '012' AND hsc_cd = '05' AND trans_type = '1'
           GROUP BY napkin_type),
    b AS (SELECT
            COALESCE(SUM(quantity), 0) AS "diverted_income",
            napkin_type
          FROM hsc_receipt_entry
          WHERE dvn_cd = '15' AND phc_cd = '012' AND to_dvn = '05' AND trans_type = '2'
          GROUP BY napkin_type),
    c AS (SELECT
            COALESCE(SUM(quantity), 0) AS "diverted_out",
            napkin_type
          FROM "hsc_receipt_entry"
          WHERE "dvn_cd" = '15' AND "phc_cd" = '012' AND "from_dvn" = '05' AND trans_type = '2'
          GROUP BY napkin_type),
    d AS (SELECT
            COALESCE(SUM(slsc_qty + non_slsc_qty + six_sc_qty + sev_sc_qty + hom_sc_qty + slst_qty + non_slst_qty +
                         six_st_qty + sev_st_qty + hom_st_qty + slot_qty + non_slot_qty + six_ot_qty + sev_ot_qty +
                         hom_ot_qty), 0) AS issue,
            napkin_type
          FROM vhn_issue
          WHERE dvn_cd = '15' AND phc_cd = '012' AND hsc_cd = '05'
          GROUP BY napkin_type)

SELECT *
FROM a, b, c, d
WHERE a.napkin_type = b.napkin_type AND a.napkin_type = c.napkin_type AND a.napkin_type = d.napkin_type;

1 个答案:

答案 0 :(得分:0)

如果我正确地解决了您的问题,我相信您应该将最终查询更改为使用LEFT OUTER JOINS而不是INNER JOINS(正如您所做的那样)。所以代替

SELECT *
FROM a, b, c, d
WHERE a.napkin_type = b.napkin_type
      AND a.napkin_type = c.napkin_type
      AND a.napkin_type = d.napkin_type;

使用:

SELECT
    a."receipt", a.napkin_type,
    COALESCE(b."diverted_income", 0), a.napkin_type,
    COALESCE(c."diverted_out", 0), a.napkin_type,
    COALESCE(d.issue, 0), a.napkin_type,
FROM a
    LEFT JOIN b ON a.napkin_type = b.napkin_type
    LEFT JOIN c ON a.napkin_type = c.napkin_type
    LEFT JOIN d ON a.napkin_type = d.napkin_type
;

请注意,我已将故意用于a.napkin_type,因为您将所有内容加入到名为a的表中,此方法会从NULLs输出中删除napkin_type