gpt4 book ai didi

mysql - MySQL 中的排名函数

转载 作者:行者123 更新时间:2023-11-29 22:46:03 25 4
gpt4 key购买 nike

我需要找出客户的排名。这里我根据我的要求添加相应的 ANSI 标准 SQL 查询。请帮我将其转换为 MySQL 。

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

MySQL中有没有查询排名的函数?

最佳答案

一种选择是使用排名变量,如下所示:

SELECT    first_name,
age,
gender,
@curRank := @curRank + 1 AS rank
FROM person p, (SELECT @curRank := 0) r
ORDER BY age;

(SELECT @curRank := 0) 部分允许变量初始化,而无需单独的 SET 命令。

测试用例:

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

结果:

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

关于mysql - MySQL 中的排名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29121425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com