db-tutorial/codes/mysql/Leetcode之SQL题/normal/分数排名.sql

56 lines
1.4 KiB
SQL
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

-- 分数排名
--
-- 编写一个 SQL 查询来实现分数排名。如果两个分数相同则两个分数排名Rank相同。
-- 请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。
--
-- +----+-------+
-- | Id | Score |
-- +----+-------+
-- | 1 | 3.50 |
-- | 2 | 3.65 |
-- | 3 | 4.00 |
-- | 4 | 3.85 |
-- | 5 | 4.00 |
-- | 6 | 3.65 |
-- +----+-------+
-- 例如,根据上述给定的 Scores 表,你的查询应该返回(按分数从高到低排列):
--
-- +-------+------+
-- | Score | Rank |
-- +-------+------+
-- | 4.00 | 1 |
-- | 4.00 | 1 |
-- | 3.85 | 2 |
-- | 3.65 | 3 |
-- | 3.65 | 3 |
-- | 3.50 | 4 |
-- +-------+------+
USE db_tutorial;
CREATE TABLE IF NOT EXISTS scores (
id INT PRIMARY KEY AUTO_INCREMENT,
score DOUBLE
);
INSERT INTO scores (score)
VALUES (3.50);
INSERT INTO scores (score)
VALUES (3.65);
INSERT INTO scores (score)
VALUES (4.00);
INSERT INTO scores (score)
VALUES (3.85);
INSERT INTO scores (score)
VALUES (4.00);
INSERT INTO scores (score)
VALUES (3.65);
SELECT count(DISTINCT b.score)
FROM scores b;
SELECT a.score AS score,
(SELECT count(DISTINCT b.score) FROM scores b WHERE b.score >= a.score) AS ranking
FROM scores a
ORDER BY a.score DESC;