Microsoft
Software
Hardware
Network
Question : SELECT TOP n of each
I want to select the TOP n records from a table for each of the possible values of another field. What is the best way to do that in a single query?
I came up with this:
SELECT TOP 5 <fields> FROM <table> WHERE <fk_field> = 1 ORDER BY insert_date
UNION
SELECT TOP 5 <fields> FROM <table> WHERE <fk_field> = 2 ORDER BY insert_date
....
(etc)
but that requires that I need to hardcode all values of <fk_field> and I do not want that. <fk_field> is a foreign key, so it is not too hard to get all possible values with a query.
I could use that in a stored procedure filling a temp_table with a number of queries. But I wonder is there is a better method.
Answer : SELECT TOP n of each
SQL Server 2005+
SELECT <fields>
FROM
(
SELECT <fields>, rn=row_number() over (partition by <fk_field> order by insert_date)
FROM <table>
) SQ
WHERE rn<=5
--ORDER BY insert_date
Random Solutions
bulk collect - amount of return
SSIS reuse the object variable
Exchange 2003 (SBS) not sending or receiving.
How to copy folders/files between computers and preserve modified date ?
Er diagram for university accommodation office
Trend Micro Officescan 10.0 on Citrix XenApp Presentation Server 4.5 or 5.0
Logging computer off network
VPN between SSG 20 and RVO42 does not come up. "ERROR: Peer did not send a proxy id"
LUN unpresented from ESX hosts causing alarms
Preparing a AD to add MAC hardware