简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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