Home >Database >Mysql Tutorial >How to Rank Customers by Age and Gender in MySQL?
Ranking Customers in MySQL: A Practical Guide
MySQL doesn't offer a built-in rank function, requiring custom queries for ranking customers by age and gender. This guide demonstrates a solution using a user-defined variable for efficient ranking.
The Query:
This query utilizes a variable to assign ranks:
<code class="language-sql">SELECT first_name, age, gender, @curRank := @curRank + 1 AS rank FROM person p, (SELECT @curRank := 0) r ORDER BY age;</code>
The clever part is the (SELECT @curRank := 0) r
subquery. This elegantly initializes the ranking variable @curRank
, eliminating the need for a separate SET
statement.
Illustrative Example:
Let's consider a sample person
table:
<code class="language-sql">CREATE TABLE person (id int, first_name varchar(20), age int, gender char(1)); INSERT INTO person VALUES (1, 'Bob', 25, 'M'); INSERT INTO person VALUES (2, 'Jane', 20, 'F'); INSERT INTO person VALUES (3, 'Jack', 30, 'M'); INSERT INTO person VALUES (4, 'Bill', 32, 'M'); INSERT INTO person VALUES (5, 'Nick', 22, 'M'); INSERT INTO person VALUES (6, 'Kathy', 18, 'F'); INSERT INTO person VALUES (7, 'Steve', 36, 'M'); INSERT INTO person VALUES (8, 'Anne', 25, 'F');</code>
Query Results:
Executing the query yields the following ranked customer data:
<code>+------------+------+--------+------+ | first_name | age | gender | rank | +------------+------+--------+------+ | Kathy | 18 | F | 1 | | Jane | 20 | F | 2 | | Nick | 22 | M | 3 | | Bob | 25 | M | 4 | | Anne | 25 | F | 5 | | Jack | 30 | M | 6 | | Bill | 32 | M | 7 | | Steve | 36 | M | 8 | +------------+------+--------+------+</code>
This clearly shows the customers ranked by age. To incorporate gender into the ranking, simply adjust the ORDER BY
clause to include gender as a secondary sorting criteria (e.g., ORDER BY age, gender
).
The above is the detailed content of How to Rank Customers by Age and Gender in MySQL?. For more information, please follow other related articles on the PHP Chinese website!