简体   繁体   English

Postgres - 计算平均每月行数

[英]Postgres - Calculate average monthly rows

I have a table that represents user's deposits into a savings account.我有一张表,代表用户在储蓄账户中的存款。 I'd like to find the average number of deposits that a user makes per month but I'm having trouble getting there.我想找到用户每月的平均存款数,但我无法到达那里。

I've tried我试过了

SELECT date_part('month', timestamp) as month FROM savings_account_deposit
WHERE user_id = :user_id
AND savings_account_id = :savings_account_id
GROUP BY date_part('month', timestamp)

but I'm actually looking for a single number that represents the average deposits per month across the lifetime of the savings account.但我实际上是在寻找一个代表储蓄账户整个生命周期内每月平均存款的数字。

You would need another level of aggregation:您将需要另一个聚合级别:

SELECT AVG(cnt) avg_deposit_per_month
FROM (
    SELECT COUNT(*) cnt 
    FROM savings_account_deposit
    WHERE user_id = :user_id AND savings_account_id = :savings_account_id
    GROUP BY date_trunc('month', timestamp)
) t

The subquery counts the number of deposits per month, then the outer query just averages the counts.子查询计算每月存款的数量,然后外部查询只是对计数进行平均。

Note that I changed date_part in your query to date_trunc : the former would aggregate together deposits of the same month in different years, which is probably not what you want.请注意,我将您查询中的date_part更改为date_trunc :前者会将不同年份的同一个月的存款汇总在一起,这可能不是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM