Postgres 生成_系列
我想要的是对表进行统计,为此我使用 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
这很有效,但是当我想应用过滤器(例如获取对于特定用户的金额我必须应用它们两次。有没有办法避免过滤两次,或者以更有效的方式重写它,因为我不确定这是否是正确的方法?
What I want to is to make statistics on a table and for this I'm using generate_series();
Here is what I'm doing:
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
This works well but when I want to apply filters like get the amount for specifics users I have to apply them twice. Is there a way to avoid filtering twice, or to rewrite this in a more efficient way because I'm not sure if it's the right way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以为此编写
WITH
查询:结果示例:
You could write
WITH
query for this:Example result:
您可以在WITH子句中执行查询,然后使用SELECT添加缺失的月份:
You can execute your query within a WITH clause and then use SELECT to add missing months: