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