【问题标题】:Postgres - Calculate average monthly rowsPostgres - 计算平均每月行数
【发布时间】:2022-12-07 07:43:17
【问题描述】:

我有一张表,代表用户在储蓄账户中的存款。我想找到用户每月的平均存款数,但我无法到达那里。

我试过了

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)

但我实际上是在寻找一个代表储蓄账户整个生命周期内每月平均存款的数字。

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    您将需要另一个聚合级别:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      相关资源
      最近更新 更多