开发者

Get the highest-n values including duplicates in SQL

开发者 https://www.devze.com 2023-03-23 19:19 出处:网络
I have a query that returns the highest-n values in a table and it works fine. Here\'s a simplified version of the query I\'m using:

I have a query that returns the highest-n values in a table and it works fine. Here's a simplified version of the query I'm using:

SELECT Series FROM SeriesScores
        ORDER BY Series DESC LIMIT 0,n

Where n is a parameter in the method that is calling the query. Of course I have other criterias to narrow down the list, but I think it is irrelevant in th开发者_开发问答is case.

The problem with this query is that it will not return the n+1th result if it is equal to the nth result.

If n = 1, I have another query using MAX and joining the table on itself so it returns every single person that has the max value in series, but I can't seem to figure something out for other n values.


You could try the following:

SELECT s1.id, s1.series FROM SeriesScores s1 
INNER JOIN 
    (SELECT DISTINCT series FROM SeriesScores ORDER BY series DESC LIMIT 0, n) as s2 
    ON s1.series = s2.series
0

精彩评论

暂无评论...
验证码 换一张
取 消