I have a table from which I want to get the top N records. Records are sorted by value, and some records have the same value. What I would like to do here is to get a list of the best N entries, including related ones. This is what is in the table:
+-------+--------+
| Name | Value |
+-------+--------+
| A | 10 |
| B | 30 |
| C | 40 |
| D | 40 |
| E | 20 |
| F | 50 |
+-------+--------+
Now, if I want to get the top 3 so
SELECT * FROM table ORDER BY Value DESC LIMIT 3
I get this:
+-------+--------+
| Name | Value |
+-------+--------+
| F | 50 |
| C | 40 |
| D | 40 |
+-------+--------+
What I would like to receive is
+-------+--------+
| Name | Value |
+-------+--------+
| F | 50 |
| C | 40 |
| D | 40 |
| B | 30 |
+-------+--------+
I calculate the rank of each record, so I'd really like to get the first N ranked records instead of the first N records sorted by value. This is how I calculate the rank:
SELECT Value AS Val, (SELECT COUNT(DISTINCT(Value))+1 FROM table WHERE Value > Val) as Rank
In T-SQL, something similar is achieved by doing this:
SELECT TOP 3 FROM table ORDER BY Value WITH TIES
- , MySQL? , , . .