题目:
表tb如下,ID为自增,查询出第一条开始到第几条记录 的累计金额刚好超过100?
table.png
参考答案:
数据库版本:Server version: 8.0.20 MySQL Community Server - GPL
建表语句
CREATE TABLE `dailytest_20200601` (
`id` int DEFAULT NULL,
`salary` int DEFAULT NULL
) ;
数据准备
INSERT INTO `dailytest_20200601` VALUES (2, 30);
INSERT INTO `dailytest_20200601` VALUES (3, 30);
INSERT INTO `dailytest_20200601` VALUES (4, 30);
INSERT INTO `dailytest_20200601` VALUES (11, 9);
INSERT INTO `dailytest_20200601` VALUES (12, 1);
INSERT INTO `dailytest_20200601` VALUES (13, 1);
INSERT INTO `dailytest_20200601` VALUES (14, 15);
INSERT INTO `dailytest_20200601` VALUES (15, 33);
INSERT INTO `dailytest_20200601` VALUES (16, 5);
INSERT INTO `dailytest_20200601` VALUES (17, 8);
INSERT INTO `dailytest_20200601` VALUES (18, 14);
INSERT INTO `dailytest_20200601` VALUES (19, 3);
查询逻辑
SELECT
AA.id,
AA.salary,
AA.balance
FROM
(
SELECT
id,
salary,
(SELECT sum(salary) FROM dailytest_20200601 WHERE id <= A.id) AS balance
FROM
dailytest_20200601 AS A
) AA
WHERE
AA.balance <= 100
网友评论