How to select top N number per date group?
I have 1 table named BookMe,
with fields
$Date, $Div, $Name
I want to select the top N number of Div's (ie highest Div value) per distinct Date.
i know how to get the distinct date like this:
SELECT DISTINCT $Date FROM BookMe ORDER BY $Date
How do I combine a TOP keyword to get the TOP n rows per distinct date?
Thx!
[376 byte] By [
ted.tea] at [2007-12-24]
You can also write the query using standard SQL like:
use Northwind
go
-- Get 2 latest orders for each customer:
select o1.*
from Orders as o1
join (select o2.CustomerID, max(o2.OrderDate) as od1 from Orders as o2 group by o2.CustomerID) as o3
on o3.CustomerID = o1.CustomerID
and o1.OrderDate in (o3.od1
, (select max(o4.OrderDate)
from Orders as o4
where o4.CustomerID = o1.CustomerID and o4.OrderDate < o3.od1)
)
And depending on your indexes / data, the query above might perform better than the count(*) or row_number version.