create table ithelp191130 (
id smallint generated always as identity primary key
, idate date not null
, grp text not null
, val smallint not null
);
insert into ithelp191130 (idate, grp, val) values
('2019/11/1'::date, 'A', 10),
('2019/11/2'::date, 'A', 20),
('2019/11/3'::date, 'A', 25),
('2019/11/4'::date, 'A', 15),
('2019/11/5'::date, 'A', 30),
('2019/11/6'::date, 'B', 11),
('2019/11/7'::date, 'B', 23),
('2019/11/8'::date, 'B', 2),
('2019/11/9'::date, 'D', 9),
('2019/11/10'::date, 'D', 7),
('2019/11/11'::date, 'D', 58),
('2019/11/12'::date, 'D', 6),
('2019/11/13'::date, 'C', 10),
('2019/11/14'::date, 'C', 10);
select idate
, grp
, val
, sum(val) over (partition by grp order by idate asc
rows between unbounded preceding and current row)
as "累加數量"
from ithelp191130
order by idate;
+------------+-----+-----+----------+
| idate | grp | val | 累加數量 |
+------------+-----+-----+----------+
| 2019-11-01 | A | 10 | 10 |
| 2019-11-02 | A | 20 | 30 |
| 2019-11-03 | A | 25 | 55 |
| 2019-11-04 | A | 15 | 70 |
| 2019-11-05 | A | 30 | 100 |
| 2019-11-06 | B | 11 | 11 |
| 2019-11-07 | B | 23 | 34 |
| 2019-11-08 | B | 2 | 36 |
| 2019-11-09 | D | 9 | 9 |
| 2019-11-10 | D | 7 | 16 |
| 2019-11-11 | D | 58 | 74 |
| 2019-11-12 | D | 6 | 80 |
| 2019-11-13 | C | 10 | 10 |
| 2019-11-14 | C | 10 | 20 |
+------------+-----+-----+----------+
(14 rows)
這種需求,
我覺得用後端寫比較快.