MySQL 窗口函数提供了一种灵活的方式来处理 SQL 查询中的数据,它们允许你在不需要对数据进行分组的情况下对行集进行分析。窗口函数最常用于分析性操作,比如计算排名、累计和、移动平均值等。MySQL 从版本 8.0 开始支持窗口函数。以下是窗口函数的几个关键概念和常见用法:
窗口函数的基本语法结构如下:sql
代码解读复制代码function_name([arguments]) OVER ([PARTITION BY columns] [ORDER BY columns] [frame_clause])
ROW_NUMBER()
, RANK()
, DENSE_RANK()
, SUM()
, AVG()
, 等。GROUP BY
。ROWS
或 RANGE
。ROW_NUMBER()
代码解读复制代码SELECT name, department,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS row_num
FROM employees;
RANK()
代码解读复制代码SELECT name, department,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank
FROM employees;
DENSE_RANK()
RANK()
,但排名不跳跃。sql 代码解读复制代码SELECT name, department,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dense_rank
FROM employees;
NTILE(n)
n
个桶中,并为每一行分配桶号。sql 代码解读复制代码SELECT name, department,
NTILE(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees;
SUM(), AVG(), MIN(), MAX()
代码解读复制代码SELECT name, department, salary,
SUM(salary) OVER (PARTITION BY department) AS total_salary
FROM employees;
窗口框架用来定义在计算聚合值时哪些行应该被包含在窗口内。框架可以用 ROWS
或 RANGE
来定义。
示例:sql
代码解读复制代码SELECT name, salary,
SUM(salary) OVER (ORDER BY salary ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS moving_sum
FROM employees;
窗口函数在以下场景中非常有用:
通过使用窗口函数,开发者可以在查询中轻松实现复杂的分析和报告功能,而不需要进行额外的数据处理。窗口函数提供了一种简洁、优雅的解决方案,可以提高 SQL 查询的表达能力和执行效率。