1. 程式人生 > 其它 >移動端基礎物理畫素、解析度、邏輯畫素、裝置畫素、縮放、ppi視口、meta

移動端基礎物理畫素、解析度、邏輯畫素、裝置畫素、縮放、ppi視口、meta

技術標籤:SQL練習資料庫sql

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

總結:如果有別的方法的小夥伴,歡迎一起來分享一下!