Introduction
Advanced window functions help you analyze data across rows without losing the original row details. They make complex calculations easier and faster.
SELECT column1, column2, window_function() OVER (PARTITION BY columnX ORDER BY columnY ROWS BETWEEN ... ) AS alias FROM table_name;
SELECT employee_id, salary, RANK() OVER (ORDER BY salary DESC) AS salary_rank FROM employees;
SELECT order_id, order_date, SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_total FROM orders;
SELECT product_id, sales, LAG(sales) OVER (ORDER BY sale_date) AS previous_sales FROM sales_data;
CREATE TABLE sales ( id INT, customer VARCHAR(20), amount INT, sale_date DATE ); INSERT INTO sales VALUES (1, 'Alice', 100, '2024-01-01'), (2, 'Alice', 150, '2024-01-05'), (3, 'Bob', 200, '2024-01-03'), (4, 'Alice', 50, '2024-01-10'), (5, 'Bob', 300, '2024-01-07'); SELECT customer, sale_date, amount, SUM(amount) OVER (PARTITION BY customer ORDER BY sale_date) AS running_total FROM sales ORDER BY customer, sale_date;
employees with columns department, salary, and name, what will the following query return?SELECT name, department, salary, RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank FROM employees;
SELECT region, sales, SUM(sales) OVER (PARTITION region ORDER BY date) AS cumulative_sales FROM sales_data;
Pass the test and this pattern moves unknown