SQL query question

Soldato
Joined
12 Jan 2004
Posts
6,824
Location
Londinium
Guys,

I want to retrieve the first two results from a table for every value of a certain column, how would I do this? :confused:
 
A mock of some sample data in the table would help (i.e. what is available to identify rows, what is the column we're using to pick first 2 samples from, and when there's more than 2 rows in a set, how would we know which 2 are the 'first', based on what ordering factor?).

Ultimately though if your DBMS permits it (provide the vendor name and version of your DBMS too), then analytics are probably what you want.

Something like this if it's a relatively recent Oracle/MSSQL backend:

select * from
(
select row_number()
over (partition by the_sample_column order by the_order_column) as row_num,
*
from your_table
) q
where q.row_num <= 2

If it's MySQL though, completely different kettle of fish.
 
Incidentally, the stuff I wrote in my reply looks like nothing that was in the article - so in case you wonder about that, it's likely only because the article was written 4.5 years ago and still covering all bases when it comes to SQL Server version compatibility.

If they were to rewrite it nowadays they'd probably opt for analytics instead (I think anyway), as it's more routinely accepted now.
 
Back
Top Bottom