从2个表中获取组合的分组计数

时间:2018-03-22 13:46:09

标签: psql

我希望将按周分组的变量(注入)的计数组合为两个单独的表(myocbp)。我可以轻松地为每个表单独执行此操作

SELECT EXTRACT (week from cbp_date) as week, count(*) FROM cbp where EXTRACT (year from cbp_date) = '2018' and cbp_injected_by = 'ABC' group by week order by week asc

SELECT EXTRACT (week from myo_date) as week, count(*) FROM myo where EXTRACT (year from myo_date) = '2018' and myo_injected_by = 'ABC' group by week order by week asc

如何将这些查询与UNION合并,并按week进行分组?

1 个答案:

答案 0 :(得分:1)

我认为加入可能实际上更有意义。下面的查询每周报告两个表中的相应计数。

WITH cte1 AS (
    SELECT EXTRACT (WEEK FROM cbp_date) AS week,
    COUNT(*) AS cbp_cnt
    FROM cbp
    WHERE EXTRACT (year from cbp_date) = '2018' AND cbp_injected_by = 'ABC'
    GROUP BY week
),
cte2 AS (
    SELECT EXTRACT (WEEK FROM myo_date) AS week,
    COUNT(*) AS myo_cnt
    FROM myo
    WHERE EXTRACT (year from myo_date) = '2018' AND myo_injected_by = 'ABC'
    GROUP BY week
)

SELECT
    t1.week,
    t1.cbp_cnt,
    t2.myo_cnt
FROM cte1 t1
LEFT JOIN cte2 t2
    ON t1.week = t2.week;

我在这里假设两个表格,特别是cbp表格,都有2018年所有周的数据,或者如果不是这样,你不介意不报告错过的周数。要获得您想要的确切输出,您可能需要加入日历表,但希望这仍然是一个有用的建议。

编辑:如果由于某种原因,您的Postgres版本不支持CTE,那么您可以加入两个子查询,例如

SELECT
    t1.week,
    t1.cbp_cnt,
    t2.myo_cnt
FROM
(
    -- cte1
) t1
LEFT JOIN
(
    -- cte2
) t2
    ON t1.week = t2.week;