[英]How to select until sum a column reaches a value?
我需要从 mysql 表中选择记录,直到总和一列达到目标值,假设我的表是
CREATE TABLE Table1
(
id int auto_increment primary key,
Date DateTime,
type int,
MyAmountCol int
);
INSERT INTO Table1
(Date, type, MyAmountCol)
VALUES
('2013-02-01 00:00:00','85482','1'),
('2013-02-01 00:00:00','47228','2'),
('2013-02-02 00:00:00','12026','4'),
('2013-02-03 00:00:00','78927','6'),
('2013-02-04 00:00:00','85662','2'),
('2013-03-05 00:00:00','47978','1'),
('2013-08-07 00:00:00','8582','1');
这是我正在尝试的 sql 查询。
SELECT
O.Id,
O.Type,
O.MyAmountCol,
(SELECT
sum(MyAmountCol) FROM Table1
WHERE Id <= O.Id) 'RunningTotal'
FROM Table1 O
HAVING RunningTotal <=8
http://sqlfiddle.com/#!9/ec160/5
但不能按需要工作,任何帮助将不胜感激。
在 MySQL 8+ 和更新版本的 MySQL 中,您可以使用窗口函数:
select t1.*
from (select t1.*,
sum(t1.amount) over (order by t1.id) as running_amount
from table1 t1
) t1
where running_amount <= 8
如果您希望第一个达到或超过8,则:
where running_amount - amount < 8
在旧版本中,您可以使用相关子查询或变量执行此操作:
select t1.*
from (select t1.*,
(select sum(tt1.amount)
from table1 tt1
where tt1.id <= t1.id
) as running_amount
from table1 t1
) t1
where running_amount <= 8;
我更喜欢子查询到having
条款,但是,这只是一个偏好。
像这样做:
;with cte as
(
select *,
sum(MyAmountCol) over(order by id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as RunningTotal from Table1
)
select * from cte where RunningTotal <= 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.