Complete the code to calculate the running total of sales ordered by date.
SELECT sales_date, amount, SUM(amount) OVER (ORDER BY [1]) AS running_total FROM sales;The OVER clause with ORDER BY sales_date calculates the running total in date order.
Complete the code to rank employees by their salary within each department.
SELECT employee_id, department_id, salary, RANK() OVER (PARTITION BY department_id ORDER BY [1] DESC) AS dept_rank FROM employees;The RANK() function ranks employees by salary descending within each department.
Fix the error in the code to calculate the cumulative average salary ordered by hire date.
SELECT employee_id, salary, AVG(salary) OVER (ORDER BY [1] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cum_avg_salary FROM employees;The cumulative average should be ordered by hire_date to calculate average salary up to each employee's hire date.
Fill both blanks to calculate the difference between each sale amount and the previous sale amount ordered by sales_date.
SELECT sales_date, amount, amount - LAG(amount) OVER (ORDER BY [1] [2]) AS diff FROM sales;
The LAG() function looks at the previous row ordered by sales_date ASC to find the difference.
Fill all three blanks to calculate the cumulative sum of sales amount partitioned by region and ordered by sales_date.
SELECT region, sales_date, amount, SUM(amount) OVER (PARTITION BY [1] ORDER BY [2] [3]) AS cum_sum FROM sales;
The cumulative sum is partitioned by region and ordered by sales_date ASC to sum sales in date order per region.