MySQL alternative to T-SQL WITH TIES

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? , , . .

+3
2

?

select Name, Value from table where Value in (
    select distinct Value from table order by Value desc limit 3
) order by Value desc

, :

select a.Name, a.Value 
from table a
join (select distinct Value from table order by Value desc limit 3) b
     on a.Value = b.Value
+5
select a.Name, a.Value 
from table a
join (select Value from table order by Value desc limit 3) b
     on a.Value = b.Value

@Fosco, DISTINCT . N , N ( ). . 50, 50, 50, 40, 40, 30, 20, 6 (3x50, 2x40, 1x30), , , 3x50.

+3

Source: https://habr.com/ru/post/1759349/


All Articles