窗口函數是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查詢的效率和靈活性。