简体   繁体   English

如何选择直到总和一列达到一个值?

[英]How to select until sum a column reaches a value?

i need to select records from a mysql table until sum a column reaches a goal value, lets assume my table is that我需要从 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');

and this is the sql query i am trying .这是我正在尝试的 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 http://sqlfiddle.com/#!9/ec160/5

but doesn't work as needed,Any help would be greatly appreciated.但不能按需要工作,任何帮助将不胜感激。

In MySQL 8+ and the more recent versions of MySQL, you can use window functions:在 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

If you want the first that reaches or exceeds 8, then:如果您希望第一个达到或超过8,则:

where running_amount - amount < 8

In older versions, you can do this with a correlated subquery or variables:在旧版本中,您可以使用相关子查询或变量执行此操作:

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;

I prefer the subquery to the having clause, but that is just a preference.我更喜欢子查询到having条款,但是,这只是一个偏好。

DO it like this:像这样做:

;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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM