交易表中的历史余额

时间:2021-07-08 11:41:24

标签: postgresql

我有下表:

<头>
customer_id 交易日期 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 交易日期 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 今天的日期 136.2

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

1 个答案:

答案 0 :(得分: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";