Mysql查询窗口函数之按序号取元素详解
需求概述
查询以课程(course)分区以分数(score)逆序的窗口里的第一个、最后一个和第2个元素对应的值。示例表数据见下:
SELECT '数学' course, 40 score, '张三' name UNION
SELECT '数学' course, 60 score, '李四' name UNION
SELECT '数学' course, 70 score, '王二' name UNION
SELECT '数学' course, 55 score, '赵钱' name UNION
SELECT '英语' course, 65 score, '张三' name UNION
SELECT '英语' course, 70 score, '李四' name UNION
SELECT '语文' course, 83 score, '张三' name
问题分析
该需求需要借助窗口函数的FIRST_VALUE、LAST_VALUE、NTH_VALUE函数来实现,其中针对窗口里的最后一个元素需要界定它的范围。
SQL代码
SELECT FIRST_VALUE(score) OVER w first_value,
LAST_VALUE(score) OVER w as last_value,
LAST_VALUE(score) OVER (
PARTITION BY course
ORDER BY score DESC
RANGE BETWEEN
UNBOUNDED PRECEDING AND
UNBOUNDED FOLLOWING) reallast_value,
NTH_VALUE(score,3) OVER w as nth_value,
score,
course
FROM
(
SELECT '数学' course, 40 score, '张三' name UNION
SELECT '数学' course, 60 score, '李四' name UNION
SELECT '数学' course, 70 score, '王二' name UNION
SELECT '数学' course, 55 score, '赵钱' name UNION
SELECT '英语' course, 65 score, '张三' name UNION
SELECT '英语' course, 70 score, '李四' name UNION
SELECT '语文' course, 83 score, '张三' name
)A
WINDOW w AS (PARTITION BY course order by score DESC)
执行结果