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;
If you are working with MySQL, and the column is of type timestamp. You need to convert it to Date and then compare it with the date you want to compare with.
SELECT * FROM tablename tName
where
Date(timestampFieldName) = Date('2009-07-08')
limit 0,10
If you're working from a programming language and not directly querying the server, you could dynamically construct a query for the union of the 'Limit 10' or 'Top 10' for each day. Not incredibly efficient, but it would at least work and be easy to debug and modify later. You could even create the query dynamically via an SP in the server and work straight from there.
Actually it´s more like this, I had misplaced the order by for the date.
Here we assume there is a datetime field in the Records table and a score field to rank records.
SELECT *
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY datepart(year, Record.date), datepart(month, Record.date), datepart(day, Record.date)
ORDER BY Record.score desc) AS row
FROM Record ) AS table1
WHERE row < 11
ORDER BY datepart(year, Record.date) desc, datepart(month, Record.date) desc, datepart(day, Record.date) desc
You have to get your 10 records per day in a subquery for each day and join them to the main table by a left join, so you'll get max 10 records per day. The SQL would look like this:
SELECT t1.columns
FROM mytable t1
LEFT JOIN
(SELECT pk FROM mytable t2
WHERE t2.datecol = t1.datecol
ORDER BY t2.orderFor10Rows LIMIT 10) t3
ON t1.pk = t3.pk
ORDER BY t1.anyOtherColumns
No warranty for proper MySQL-syntax as I'm not used to it.
Here is a possible solution, but it will require a little work outside of sql. This is from a live example of a list of movies. All you need to do after this is pull the first 10 movies of the concatenated list.
SELECT Movie_Release_Year, GROUP_CONCAT( Movie_Title
ORDER BY Movie_Title )
FROM movies
GROUP BY Movie_Release_Year
see Group Concat for more details