【问题标题】:Historical Balance from a transactaion table交易表中的历史余额
【发布时间】:2021-07-08 11:41:24
【问题描述】:

我有下表:

customer_id transacting date day_end_balance
523161 7/2/2021 136.2
523161 6/14/2021 215.4
523161 6/7/2021 0
523161 6/2/2021 440

所以余额会在交易发生时显示,如果没有交易发生,余额在一天结束时保持不变。我想创建一个表格,显示从客户生命之初到今天每个客户的日终余额。检查下表以获得所需的输出。

customer_id transacting date day_end_balance
523161 6/2/2021 440
523161 6/3/2021 440
...... ............ .....
523161 6/7/2021 0
523161 6/8/2021 0
523161 6/9/2021 0
523161 6/10/2021 0
523161 6/11/2021 0
523161 6/12/2021 0
523161 6/13/2021 0
523161 6/14/2021 215.4
523161 6/14/2021 215.4
523161 6/15/2021 215.4
523161 6/16/2021 215.4
523161 6/17/2021 215.4
523161 6/18/2021 215.4
523161 6/19/2021 215.4
523161 6/20/2021 215.4
523161 6/21/2021 215.4
523161 6/22/2021 215.4
523161 6/23/2021 215.4
523161 6/24/2021 215.4
523161 6/25/2021 215.4
523161 6/26/2021 215.4
523161 6/27/2021 215.4
523161 6/28/2021 215.4
523161 6/29/2021 215.4
523161 6/30/2021 215.4
523161 7/1/2021 215.4
523161 7/2/2021 136.2
523161 .... 136.2
523161 date of today 136.2

我如何在 postgres sql 中执行此操作?我知道它会涉及 last_value() 和 coalesce(),可能还有 lag() 和 lead()。但是不知道怎么写。

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    您可以使用generate_series() 获取客户的最短日期和今天之间的所有天数,并横向连接选择小于或等于系列中相应日期的最长日期的数据。

    SELECT cjl."customer_id",
           gs."transacting date",
           cjl."day_end_balance"
           FROM generate_series((SELECT min(t."transacting date")
                                        FROM elbat t
                                        WHERE t."customer_id" = 523161),
                                current_date,
                                '1 day'::interval) gs
                                                   ("transacting date")
                CROSS JOIN LATERAL (SELECT t."customer_id",
                                           t."day_end_balance"
                                           FROM elbat t
                                           WHERE t."customer_id" = 523161
                                                 AND t."transacting date" <= gs."transacting date"
                                           ORDER BY t."transacting date" DESC
                                           LIMIT 1) cjl
           ORDER BY gs."transacting date";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-09
      • 2019-03-28
      • 1970-01-01
      • 2023-03-14
      • 2021-04-28
      • 2013-09-15
      • 2013-05-04
      • 1970-01-01
      相关资源
      最近更新 更多