将查询合并为一体

时间:2019-06-18 20:16:35

标签: postgresql

我有两个返回不同结果的查询,我想将它们合并,但是我仍在学习如何用postgreSQ编写,因此这样做有些麻烦。我的查询是:

  1. 此列表返回直到当前月份为止的所有月份的列表。
SELECT * FROM generate_series('2019-01-01', now(), '1 month')

EXAMPLE:

    generate_series 
------------------------ 
2019-01-01 00:00:00+00
2019-02-01 00:00:00+00
2019-03-01 00:00:00+00
2019-04-01 00:00:00+00
  1. 此人返回该月内注册人数的计数。但这只是返回月份不为零的月份。
SELECT date_trunc('MONTH', (date_signed_up::date)) AS monthly, count(id) AS count FROM customer 
WHERE group_id = 1
GROUP BY monthly
ORDER BY monthly asc

EXAMPLE:

     monthly           | count
-----------------------------------
2019-01-01 00:00:00+00 |   3
2019-02-01 00:00:00+00 |   1
2019-04-01 00:00:00+00 |   1

期望的结果或我需要的是具有这样的表:

     monthly           | count
-----------------------------------
2019-01-01 00:00:00+00 |   3
2019-02-01 00:00:00+00 |   1
2019-03-01 00:00:00+00 |   0
2019-04-01 00:00:00+00 |   1
2019-05-01 00:00:00+00 |   0

..etc

1 个答案:

答案 0 :(得分:1)

SELECT period monthly, count(id) count 
    FROM generate_series('2019-01-01', now(), '1 month') p (period)
        LEFT JOIN customer 
            ON p.period = date_trunc('MONTH', (date_signed_up::date)) AND group_id = 1
    GROUP BY monthly
    ORDER BY monthly asc