Rank functions in MySQL
Rank functions in MySQL are window functions that allow you to assign a rank to each row within a partition of a result set. These functions are particularly useful for performing calculations based on the order of rows, such as finding the highest or lowest values, and they can help you easily categorize data without needing to create complex subqueries.
Types of Rank Functions
2. DENSE_RANK():
3. ROW_NUMBER():
Syntax
The syntax for using these functions is as follows:
领英推荐
RANK() OVER (PARTITION BY column ORDER BY column)
DENSE_RANK() OVER (PARTITION BY column ORDER BY column)
ROW_NUMBER() OVER (PARTITION BY column ORDER BY column)
Suppose you have a scores table with the following structure and data:
-- Create the scores table
CREATE TABLE scores (
student_id INT,
subject VARCHAR(50),
score INT
)ENGINE=InnoDB;
-- Insert data into the scores table
INSERT INTO scores (student_id, subject, score) VALUES
(1, 'Math', 95),
(2, 'Math', 85),
(3, 'Math', 95),
(4, 'Math', 75),
(1, 'Science', 90),
(2, 'Science', 88),
(3, 'Science', 90);B;
Query Example
To assign ranks to students based on their scores in each subject, you could use:
SELECT
student_id,
subject,
score,
RANK() OVER (PARTITION BY subject ORDER BY score DESC) AS ranking,
DENSE_RANK() OVER (PARTITION BY subject ORDER BY score DESC) AS denseRank,
ROW_NUMBER() OVER (PARTITION BY subject ORDER BY score DESC) AS rowNumber
FROM
scores;
Result Explanation
This query would produce the following results:
Summary
These functions are powerful tools for analysis and reporting, allowing you to easily segment and rank your data based on various criteria.