Complete the code to calculate the running total of sales.
SELECT sales, SUM(sales) OVER (ORDER BY date [1]) AS running_total FROM sales_data;The clause ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW defines the window frame for the running total.
Complete the code to rank employees by their sales within each department.
SELECT employee, department, sales, RANK() OVER ([1] department ORDER BY sales DESC) AS sales_rank FROM employee_sales;PARTITION BY divides the data into groups (departments) for ranking.
Fix the error in the code to calculate the difference between current and previous sales.
SELECT date, sales, sales - LAG(sales) OVER (ORDER BY [1]) AS sales_diff FROM sales_data;The ORDER BY inside the window function should use the date to get the previous row correctly.
Fill both blanks to calculate the average sales per department and show the difference from each sale.
SELECT employee, department, sales, AVG(sales) OVER ([1] department [2]) AS avg_dept_sales FROM employee_sales;
PARTITION BY department groups sales by department, and the window frame ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING defines the range for averaging.
Fill all three blanks to calculate cumulative sales per department ordered by date.
SELECT employee, department, sales, SUM(sales) OVER ([1] department [2] [3]) AS cumulative_sales FROM employee_sales;
The PARTITION BY department groups rows, ORDER BY date orders them, and the window frame ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW defines the cumulative range.