2列的累积总和

时间:2020-05-29 12:56:39

标签: postgresql

我正在使用Postgresql 11。

我有2个表-txn_table和summary_table

create table txn_table(id int, txn_date timestamp, amount decimal);

create table summary_table(id int, txn_date date, day_Total decimal, Cumulative_Total decimal);

txn_table的样本数据为

insert into txn_table values (1, '2020-05-28 10:05:05', 100.00);
insert into txn_table values(2, '2020-05-28 11:45:10', 200.00);
insert into txn_table values(3, '2020-05-29 10:05:05', 300.00);
insert into txn_table values(4, '2020-05-29 12:10:01', 400.00);

我想像下面那样将数据插入summary_table中

  1. day_total包含特定日期的总和
  2. Cumulative_total包含day_total的累积总和
| id  | txn_date                 | day_total | cumulative_total |
| --- | ------------------------ | --------- | ---------------- |
| 1   | 2020-05-28               | 300       | 300              |
| 2   | 2020-05-29               | 700       | 1000             |

2 个答案:

答案 0 :(得分:1)

我想这个选择可以解决您的问题:

insert into summary_table
select row_number() over w as id
     , txn_date
     , day_total
     , sum(day_total) over w as cumulative_total
from (
  select txn_date::date as txn_date, sum(amount) as day_total
  from txn_table
  group by txn_date::date
) d
window w as (order by txn_date)
order by txn_date

(我想出了办法,没有尝试。也许用示例输入准备数据库小提琴或CTE。)

答案 1 :(得分:0)

执行以下操作:

txn_date的{​​{1}}列添加唯一约束。

summary_table

如果要忽略重复项。使用下面提到的查询

create table summary_table(id SERIAL PRIMARY KEY, txn_date date unique, day_total decimal, cumulative_total decimal);

如果要更新insert into summary_table(txn_date,day_total,cumulative_total) (select txn_date, day_total, sum(day_total) over (order by txn_date) as cumulative_total from ( select txn_date::date as txn_date, sum(amount) as day_total from txn_table group by txn_date::date ) d order by txn_date) on conflict(txn_date) do nothing; 中的重复值。使用下面提到的查询

summary_table