CREATE TABLE IF NOT EXISTS `table` (
`date` date NOT NULL,
`count` int(11) NOT NULL,
`sum` int(11) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `table` (`date`, `count`, `sum`, `id`) VALUES
('2000-01-01', 10, 10, 1),
('2001-01-01', 10, 10, 2),
('2002-01-01', 10, 10, 3);
SELECT `date` , sum( `count` ) , `sum`
FROM `table`
GROUP BY `id`
HAVING sum( `count` ) <=15
ORDER BY `date` DESC
LIMIT 0 , 30
date sum(`count`) sum
2002-01-01 10 10
2001-01-01 10 10
2000-01-01 10 10
CREATE TABLE IF NOT EXISTS `table` (
`date` date NOT NULL,
`count` int(11) NOT NULL,
`sum` int(11) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `table` (`date`, `count`, `sum`, `id`) VALUES
('2000-01-01', 10, 10, 1),
('2001-01-01', 10, 10, 2),
('2002-01-01', 10, 10, 3);
SET @all_sum = 0;
SELECT `date`,`count`,`sum` FROM (
SELECT *, @all_sum:=@all_sum + `sum` AS mysum FROM `table` ORDER BY `date` DESC
) t
WHERE mysum < 15;
date count sum
2002-01-01 10 10