[英]MySQL get row when certain limit has been reached
我很想解決以下問題。
我們正在尋找一個查詢,當SUM(price_total)達到按類型分組的特定級別時,它將檢索數據。 表結構如下:
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;
數據
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);
閾值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
總結一下。 我想知道他們越過門檻的日期。 總價應按時間順序匯總。
這是一個簡單的自我解釋查詢:
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
演示: http : //rextester.com/GMAK8269
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.