Row Number and Group By using variables in Select Statement
suggest changeLet’s say we have a table team_person as below:
+======+===========+
| team | person |
+======+===========+
| A | John |
+------+-----------+
| B | Smith |
+------+-----------+
| A | Walter |
+------+-----------+
| A | Louis |
+------+-----------+
| C | Elizabeth |
+------+-----------+
| B | Wayne |
+------+-----------+
CREATE TABLE team_person AS SELECT 'A' team, 'John' person
UNION ALL SELECT 'B' team, 'Smith' person
UNION ALL SELECT 'A' team, 'Walter' person
UNION ALL SELECT 'A' team, 'Louis' person
UNION ALL SELECT 'C' team, 'Elizabeth' person
UNION ALL SELECT 'B' team, 'Wayne' person;
To select team_person with an additional row_number column, either. Assigning user variables in the SELECT list is deprecated, and the optimizer may not evaluate them left to right. MySQL 8.0 can number rows with ROW_NUMBER() OVER ().
SELECT @row_no := @row_no+1 AS row_number, team, person
FROM team_person, (SELECT @row_no := 0) t;
OR
SET @row_no := 0;
SELECT @row_no := @row_no + 1 AS row_number, team, person
FROM team_person;
will output the result below:
+============+======+===========+
| row_number | team | person |
+============+======+===========+
| 1 | A | John |
+------------+------+-----------+
| 2 | B | Smith |
+------------+------+-----------+
| 3 | A | Walter |
+------------+------+-----------+
| 4 | A | Louis |
+------------+------+-----------+
| 5 | C | Elizabeth |
+------------+------+-----------+
| 6 | B | Wayne |
+------------+------+-----------+
Finally, if we want to get the row_number group by column team
SELECT @row_no := IF(@prev_val = t.team, @row_no + 1, 1) AS row_number
,@prev_val := t.team AS team
,t.person
FROM team_person t,
(SELECT @row_no := 0) x,
(SELECT @prev_val := '') y
ORDER BY t.team ASC,t.person DESC;
+============+======+===========+
| row_number | team | person |
+============+======+===========+
| 1 | A | Walter |
+------------+------+-----------+
| 2 | A | Louis |
+------------+------+-----------+
| 3 | A | John |
+------------+------+-----------+
| 1 | B | Wayne |
+------------+------+-----------+
| 2 | B | Smith |
+------------+------+-----------+
| 1 | C | Elizabeth |
+------------+------+-----------+
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents