Vertex x lines and groups (again)

I know this is a common question, but I just can't figure it out, and the examples I found did not help. What I learned, the best strategy is to try to find the upper and lower values ​​of the upper range, and then select the rest, but the implementation is a bit complicated.

Example table:

id | title | group_id | votes

I would like to get the top three rows from the table for each group.

I expect this result:

91 | hello1 | 1 | 10 
28 | hello2 | 1 | 9
73 | hello3 | 1 | 8 
84 | hello4 | 2 | 456
58 | hello5 | 2 | 11 
56 | hello6 | 2 | 0 
17 | hello7 | 3 | 50
78 | hello8 | 3 | 9 
99 | hello9 | 3 | 1 

I am fond of complex queries and examples, but they really did not help.

+3
source share
1 answer

You can do this with variables:

SELECT
   id,
   title,
   group_id,
   votes
FROM (
    SELECT
        id,
        title,
        group_id,
        votes,
        @rn := CASE WHEN @prev = group_id THEN @rn + 1 ELSE 1 END AS rn,
        @prev := group_id
    FROM table1, (SELECT @prev := -1, @rn := 0) AS vars
    ORDER BY group_id DESC, votes DESC
) T1
WHERE rn <= 3
ORDER BY group_id, votes DESC

This is basically the same as the following query in databases supporting ROW_NUMBER:

SELECT
   id,
   title,
   group_id,
   votes
FROM (
     SELECT
        id,
        title,
        group_id,
        votes,
        ROW_NUMBER() OVER (PARTITION BY group_id ORDER BY votes DESC) AS rn
     FROM student
) T1
WHERE rn <= 3
ORDER BY group_id, votes DESC

MySQL ROW_NUMBER, . . , , , .

+3

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


All Articles