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
If you just need ten rows — any ten rows, you don't care which, and there is no guarantee they're random, you can use the LIMIT
clause. Example:
SELECT whatever
FROM tablename
WHERE datecol = '2009-07-13'
LIMIT 10
That'll give you ten rows. Its up to MySQL which ten. You can use ORDER BY
or additional WHERE
items to pick a certain 10. For example, here is the most recent 10:
SELECT whatever
FROM tablename
WHERE datecol = '2009-07-13'
ORDER BY timecol DESC
LIMIT 10
LIMIT
is documented as part of the SELECT syntax.
After looking at (the ever excellent) xaprb blog from Baron Schwarz, http://www.xaprb.com/blog/2006/12/02/how-to-number-rows-in-mysql/ I wonder if the use of user-defined variables could work here.
select hiredate, ename, sal
from ( select hiredate, ename, sal,
@num := if(@hiredate = hiredate, @num + 1, 1) as row_number,
@hiredate := hiredate as dummy
from emp_temp
) as x
where row_number < 3
order by hiredate, ename, sal
I've only tried the above for small sets of data, but it seems to work in bringing back just two records per hiredate. So far as I can tell from limited testing it should scale up for greater data sets. ( there may be performance issues in large data sets as Mysql is creating a temporary table)
To select the top 10 records for each day ordered by days in SQL Server 2005
select * from
(select *,ROW_NUMBER()
OVER
(PARTITION BY record.day order by record.day desc,record.score desc)
as row from record)
as table1 where row < 11
Now since your record table doesn´t have a day column as such, you need to use something like datepart(day, record.date)
instead of record.day
This should solve your problem