SQL 刷题(CREATE FUNCTION,rank)

编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。

SQL 刷题(CREATE FUNCTION,rank)

IFNULL(expression, alt_value)

select IFNULL((SELECT distinct Salary from Employee order by Salary desc limit 1 offset 1),NULL) as SecondHighestSalary

第N高的薪水

创建自定义函数

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
SET N=N-1;
  RETURN (
      # Write your MySQL query statement below.
      select ifnull(
        (select distinct Salary from  Employee order by Salary desc limit 1 offset N),null) 
  );
END

编写一个 SQL 查询来实现分数排名。

方法1:表关联查询

select s1.Score ,count(distinc s2.score) as `Rank`
from Scores s1,Scores s2
where s1.score<=s2.score
group by s1.id
order by `Rank`

方法2: 使用函数 DENSE_RANK 实现

区别RANK,DENSE_RANK和ROW_NUMBER

区别

SQL 刷题(CREATE FUNCTION,rank)
RANK并列跳跃排名,并列即相同的值,相同的值保留重复名次,遇到下一个不同值时,跳跃到总共的排名。
DENSE_RANK并列连续排序,并列即相同的值,相同的值保留重复名次,遇到下一个不同值时,依然按照连续数字排名。
ROW_NUMBER连续排名,即使相同的值,依旧按照连续数字进行排名。

分组排名

将数据分组后排名,区别如图:
SQL 刷题(CREATE FUNCTION,rank)

准备数据

创建一张分数表,里面有字段:分数score,课程号course_id和学生号student_id。
执行如下SQL语句,进行导入数据。
DECIMAL(A,B) 表示 列可以存储B位小数的A位数。十进制列的实际范围取决于精度和刻度。

CREATE TABLE score(
  student_id VARCHAR(10),
  course_id VARCHAR(10),
  score DECIMAL(18,1)
);

INSERT INTO score VALUES(‘01‘ , ‘01‘ , 80);
INSERT INTO score VALUES(‘01‘ , ‘02‘ , 90);
INSERT INTO score VALUES(‘01‘ , ‘03‘ , 99);
INSERT INTO score VALUES(‘02‘ , ‘01‘ , 70);
INSERT INTO score VALUES(‘02‘ , ‘02‘ , 60);
INSERT INTO score VALUES(‘02‘ , ‘03‘ , 80);
INSERT INTO score VALUES(‘03‘ , ‘01‘ , 80);
INSERT INTO score VALUES(‘03‘ , ‘02‘ , 80);
INSERT INTO score VALUES(‘03‘ , ‘03‘ , 80);
INSERT INTO score VALUES(‘04‘ , ‘01‘ , 50);
INSERT INTO score VALUES(‘04‘ , ‘02‘ , 30);
INSERT INTO score VALUES(‘04‘ , ‘03‘ , 20);
INSERT INTO score VALUES(‘05‘ , ‘01‘ , 76);
INSERT INTO score VALUES(‘05‘ , ‘02‘ , 87);
INSERT INTO score VALUES(‘06‘ , ‘01‘ , 31);
INSERT INTO score VALUES(‘06‘ , ‘03‘ , 34);
INSERT INTO score VALUES(‘07‘ , ‘02‘ , 89);
INSERT INTO score VALUES(‘07‘ , ‘03‘ , 98);
INSERT INTO score VALUES(‘08‘ , ‘02‘ , 89);
INSERT INTO score VALUES(‘09‘ , ‘02‘ , 89);

连续排名示例

SELECT score,
ROW_NUMBER() over (ORDER BY score DESC) `rank`
FROM `score`;

分组排名

SELECT course_id, score,
ROW_NUMBER() OVER (PARTITION BY course_id ORDER BY score DESC) ranking FROM score;

SELECT course_id, score,
RANK() OVER(PARTITION BY course_id ORDER BY score DESC)
FROM score;

SQL 刷题(CREATE FUNCTION,rank)

SQL 刷题(CREATE FUNCTION,rank)

上一篇:美赛 8:模拟退火算法、遗传算法、粒子群算法(智能算法篇)


下一篇:and和or的闰算顺序