我想要的是在桌面上进行统计,为此我正在使用generate_series();
以下是我正在做的事情:
SELECT x.month, amount
FROM (SELECT generate_series(
min(date_trunc('month', date)),
max(date_trunc('month', date)),
'1 month'
) AS month
FROM table
WHERE user_id = 55 AND ...
) x
LEFT JOIN (
SELECT SUM(amount) AS amount, date_trunc('month', date) AS month
FROM table
WHERE user_id = 55 AND ...
GROUP BY month
) q ON q.month = x.month
ORDER BY month
这很有效,但是当我想应用过滤器时,如需获取特定用户的数量,我必须将它们应用两次。有没有办法避免过滤两次,或者以更有效的方式重写它,因为我不确定它是否是正确的方法呢?
答案 0 :(得分:9)
您可以为此写WITH
query:
WITH month_amount AS
(
SELECT
sum(amount) AS amount,
date_trunc('month', date) AS month
FROM Amount
WHERE user_id = 55 -- AND ...
GROUP BY month
)
SELECT month, amount
FROM
(SELECT generate_series(min(month), max(month), '1 month') AS month
FROM month_amount) x
LEFT JOIN month_amount
USING (month)
ORDER BY month;
示例结果:
SELECT * FROM amount WHERE user_id = 55;
amount_id | user_id | amount | date
-----------+---------+--------+------------
3 | 55 | 7 | 2011-03-16
4 | 55 | 5 | 2011-03-22
5 | 55 | 2 | 2011-05-07
6 | 55 | 18 | 2011-05-27
7 | 55 | 4 | 2011-06-14
(5 rows)
WITH month_amount ..
month | amount
------------------------+--------
2011-03-01 00:00:00+01 | 12
2011-04-01 00:00:00+02 |
2011-05-01 00:00:00+02 | 20
2011-06-01 00:00:00+02 | 4
(4 rows)
答案 1 :(得分:6)
您可以在WITH子句中执行查询,然后使用SELECT添加缺少的月份:
WITH query AS (
SELECT SUM(amount) AS amount, date_trunc('month', date) AS month
FROM table
WHERE user_id = 55 AND ...
GROUP BY month
)
SELECT date(d.month) AS month, q.amount
FROM (
SELECT generate_series(min(month), max(month), '1 month') AS month
FROM query
) d
LEFT JOIN query q ON q.month = d.month
ORDER BY month