i have a db with records with date (timestamp) i need to select 10 records for each day (there are many more per day) and order them by few columns...
how should that qu
old question, but I found magnificient answer ( not my own ) using session variables.
Considering table
CREATE TABLE `report` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`reportDate` int(11) DEFAULT NULL,
`count` int(11) DEFAULT NULL,
`parameter` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `INDEX1` (`reportDate`,`parameter`,`count`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
Following query will select top 10 parameter per day based on their counts on that day
SELECT parameter, reportDate, count
FROM
(SELECT parameter,
reportDate,
count,
@reportDate_rank := IF(@current_reportDate = reportDate,@reportDate_rank + 1, 1) AS reportDate_rank,
@current_reportDate := reportDate
FROM report
ORDER BY reportDate, count DESC
) dateRanked
WHERE reportDate_rank <= 10;