【发布时间】:2020-07-23 00:33:07
【问题描述】:
我有费用和预算表。不同的记录可能有不同的预算 如果超过记录中的预算,我不想增加运行总和。
就像分区中的总和大于预算一样,它停止增加,然后在预算更大时再次增加。
有可能吗?
create table spend
(id number,
cents number,
budget number);
insert into spend(id,cents,budget) values(1,25,50);
insert into spend(id,cents,budget) values(2,25,50);
insert into spend(id,cents,budget) values(3,25,50);
insert into spend(id,cents,budget) values(4,25,50);
insert into spend(id,cents,budget) values(5,25,100);
insert into spend(id,cents,budget) values(6,25,100);
insert into spend(id,cents,budget) values(7,25,100);
insert into spend(id,cents,budget) values(8,25,200);
insert into spend(id,cents,budget) values(9,25,200);
这就是我得到的
vadimzilberleyb#TRANSFORM_WH@INSTADATA.DWH>select s.*, sum(cents) over(order by id) from spend s;
+----+-------+--------+------------------------------+
| ID | CENTS | BUDGET | SUM(CENTS) OVER(ORDER BY ID) |
|----+-------+--------+------------------------------|
| 1 | 25 | 50 | 25 |
| 2 | 25 | 50 | 50 |
| 3 | 25 | 50 | 75 |
| 4 | 25 | 50 | 100 |
| 5 | 25 | 100 | 125 |
| 6 | 25 | 100 | 150 |
| 7 | 25 | 100 | 175 |
| 8 | 25 | 200 | 200 |
| 9 | 25 | 200 | 225 |
+----+-------+--------+------------------------------+
这就是我想要的:)
id cents budget cumul in run cumulative desirable in run
1 25 50 25 25
2. 25 50 50 50
3 25 50 75 50
4 25 50 100 50
5 25 100 125 75
6 25 100 150 100
7 25 100 175 100
8 25 200 200 125
9 25 200 225 150
【问题讨论】:
-
你知道预算是否总是会被击中吗?
-
并非总是如此。至少最大的可能不会
标签: sql sum snowflake-cloud-data-platform window-functions recursive-query