简体   繁体   English

达到特定限制时,MySQL获取行

[英]MySQL get row when certain limit has been reached

I'm getting an headache of solving the following problem. 我很想解决以下问题。

We are looking for a query where it retrieves a the data when the SUM(price_total) reached a certain level grouped by type. 我们正在寻找一个查询,当SUM(price_total)达到按类型分组的特定级别时,它将检索数据。 Table structures are as followed: 表结构如下:

CREATE TABLE `Table1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Date` datetime DEFAULT NULL,
  `type` int(11) DEFAULT NULL,
  `price_total` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;

Data 数据

INSERT INTO `Table1` (`id`, `Date`, `type`, `price_total`)
VALUES
    (1,'2013-02-01 00:00:00',1,5),
    (2,'2013-02-01 00:00:00',2,15),
    (3,'2013-02-02 00:00:00',1,25),
    (4,'2013-02-03 00:00:00',3,5),
    (5,'2013-02-04 00:00:00',4,15),
    (6,'2013-03-05 00:00:00',1,20),
    (7,'2013-08-07 00:00:00',4,15);

Example outcome for threshold 15, in chronological order. 阈值15的示例结果,按时间顺序排列。

Type 1: 2013-02-02 00:00:00 Because here it came above 15. (15+5)
Type 2: 2013-02-01 00:00:00
Type 3: n/a SUM(price_total) < 15
Type 4: 2013-02-04 00:00:00

To sum up. 总结一下。 I want to know the date that they crossed the threshold. 我想知道他们越过门槛的日期。 Price total should be summed up in chronological order. 总价应按时间顺序汇总。

Here's a simple, self explanatory query: 这是一个简单的自我解释查询:

select type, min(date) as date
from (
    select t1.type, t1.date, sum(t2.price_total) as total
    from table1 t1
    join table1 t2
      on  t2.type  = t1.type
      and t2.date <= t1.date
    group by t1.type, t1.date
    having total >= 15
) sub
group by type

Demo: http://rextester.com/GMAK8269 演示: http//rextester.com/GMAK8269

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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