Postgres generate_series [英] Postgres generate_series

查看:67
本文介绍了Postgres generate_series的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要在表上进行统计,为此,我正在使用 generate_series();

What I want to is to make statistics on a table and for this I'm using 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

这很好,但是当我要应用过滤器(例如获取特定用户的金额)时,必须两次应用它们。有一种方法可以避免过滤两次,或者以更有效的方式重写它,因为我不确定这样做是否正确?

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?

推荐答案

您可以编写 WITH 查询

You could write WITH query for this:

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)

这篇关于Postgres generate_series的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆