Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

I need to find out the rank of customers. Here I am adding the corresponding ANSI standard SQL query for my requirement. Please help me to convert it to MySQL.

SELECT RANK() OVER (PARTITION BY Gender ORDER BY Age) AS [Partition by Gender], 

  FirstName, 

  Age,

  Gender 

FROM Person

Is there any function to find out rank in MySQL?

1 Answer

0 votes
by (40.7k points)

You can try using the ranking variable, like this:

SELECT    first_name,

          age,

          gender,

          @curRank := @curRank + 1 AS rank

FROM      person p, (SELECT @curRank := 0) r

ORDER BY  age;

Here, (SELECT @curRank := 0) this part allows the variable initialization without requiring the separate SET command.

Test case is as follows:

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');

Output:

+------------+------+--------+------+

| 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 |

+------------+------+--------+------+

8 rows in set (0.02 sec)

Related questions

0 votes
1 answer
asked Jan 6, 2021 in SQL by Appu (6.1k points)
0 votes
1 answer
asked Nov 19, 2020 in SQL by Vamsee Krishna (22.5k points)
0 votes
1 answer
0 votes
1 answer
asked Jan 6, 2021 in SQL by Appu (6.1k points)
0 votes
1 answer
asked Jan 5, 2021 in SQL by Appu (6.1k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...