窗口函数是SQL中的一个强大特性,它可以用来在数据集中执行一些聚合操作,比如计算排名、累积总和等。在使用窗口函数时,需要使用OVER子句来定义窗口范围,以确定哪些行将被包含在计算中。
以下是一些常见的窗口函数的应用示例:
SELECT
department_id,
employee_id,
salary,
AVG(salary) OVER (PARTITION BY department_id) AS avg_salary
FROM employees;
SELECT
employee_id,
salary,
RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;
SELECT
order_date,
SUM(sales_amount) OVER (ORDER BY order_date) AS cumulative_sales_amount
FROM sales_data;
SELECT
department_id,
sales_amount,
sales_amount / SUM(sales_amount) OVER (PARTITION BY department_id) AS sales_percentage
FROM sales_data;
以上是一些窗口函数的应用示例,窗口函数可以极大地简化数据分析和报表生成过程,提高SQL查询的效率和灵活性。