我头疼解决以下问题。
我们正在寻找一个查询,当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
总结一下。我想知道他们越过门槛的日期。价格总和应按时间顺序总结。
答案 0 :(得分:0)
这是一个简单,自我解释的问题:
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