語言輸出nm的矩陣蛇形_統計學導論-R語言實驗(1)
阿新 • • 發佈:2021-01-16
SQL練習題一(逐行累計)
表table1如下,ID為自增,查詢出第一條開始到第幾條記錄的累計金額剛好超過100?
下面是建立表語句:
CREATE TABLE table1 (
ID INT,
金額 INT
)
INSERT INTO table1 VALUES (1,30);
INSERT INTO table1 VALUES (2,30);
INSERT INTO table1 VALUES (4,30);
INSERT INTO table1 VALUES (8,9);
INSERT INTO table1 VALUES (11,1);
INSERT INTO table1 VALUES (12,1);
INSERT INTO table1 VALUES (14,15);
INSERT INTO table1 VALUES (15,33);
INSERT INTO table1 VALUES (16,5);
INSERT INTO table1 VALUES (17,8);
INSERT INTO table1 VALUES (18,14);
INSERT INTO table1 VALUES (19,3);
我這裡用的方法是先進行逐行累計,再進行對比找出目標ID
1.用錶鏈接實現
select min(id) from
(select
a.id
,a.金額
,sum(b.金額) 累計金額
from table1 a,table1 b
where a.id>=b.id
group by a.id,a.金額 having sum(b.金額)>100
order by a.id) a
2.用開窗函式實現
select
id
from
(select
id
,金額
,sum(金額) over(order by id) 累計金額
from table1
group by id,金額) a
where 累計金額>100
order by id limit 1
總結:如果有別的方法的小夥伴,歡迎一起來分享一下!