select 10 rows per day with order

前端 未结 9 541
感情败类
感情败类 2021-02-06 16:08

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

9条回答
  •  感情败类
    2021-02-06 16:25

    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;
    

提交回复
热议问题