Reputation: 2899
I have a table that I have collected of statistics, with 3 columns: id, year, and points. I would like to get the top N rows ordered by points per year. In the real scenario, there are more columns, but if I can get the ID and year, and get the rest using a subselect. Is there an easier way to do this rather than doing each year individually?
Upvotes: 0
Views: 69
Reputation: 93694
You can use the OVER clause
with window functions
to top N per group results
;WITH cte
AS (SELECT Row_number()
OVER(
partition BY year
ORDER BY points Desc) Rn,
*
FROM tablename)
SELECT *
FROM cte
WHERE rn <= 10
Upvotes: 2