Home > Database > Mysql Tutorial > body text

How to Generate Row Numbers for Grouped Data in MySQL?

Linda Hamilton
Release: 2024-11-11 12:42:03
Original
857 people have browsed it

How to Generate Row Numbers for Grouped Data in MySQL?

Row Number Generation for Grouped Data in MySQL

Assigning sequential row numbers to data grouped by specific columns is a valuable technique for efficient data manipulation and presentation. In this scenario, you want to generate row numbers for a set of data based on both the crew_id and type columns.

To achieve this, utilize the following custom query:

SELECT    id,
          crew_id,
          amount,
          type,
          ( 
             CASE type 
             WHEN @curType 
             THEN @curRow := @curRow + 1 
             ELSE @curRow := 1 AND @curType := type END
           ) + 1 AS rank
FROM      Table1 p,
          (SELECT @curRow := 0, @curType := '') r
ORDER BY  crew_id,type asc;
Copy after login

Let's break down the query step by step:

  1. Subquery: The custom query begins with a subquery defined by (SELECT @curRow := 0, @curType := '') r. This initializes two user-defined variables, @curRow and @curType, setting them to 0 and an empty string, respectively. These variables keep track of the row number and encountered type values.
  2. Outer Query: The main query, represented by SELECT id, crew_id, ..., retrieves the required data from the Table1 table. The main focus here is the calculation of the rank column.
  3. Nested CASE Statement: The CASE statement within the rank calculation checks if the current type value matches the previously encountered type (@curType). If they match, it increments @curRow by 1 and assigns the incremented value to rank. However, if type is different, it resets @curRow to 1 and updates @curType to the current type value. This ensures accurate row numbering within each group defined by crew_id and type.
  4. ORDER BY Clause: The final result is sorted in ascending order based on crew_id and type, which is crucial for proper row number allocation within each group.

By following this comprehensive query, you can efficiently generate row numbers for data groups defined by multiple columns, providing a versatile solution for data manipulation and presentation tasks in MySQL.

The above is the detailed content of How to Generate Row Numbers for Grouped Data in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template