Complete the code to calculate the running total of sales using a window function.
SELECT sales, SUM(sales) OVER (ORDER BY [1]) AS running_total FROM sales_data;The running total should be ordered by the date to accumulate sales over time.
Complete the code to assign a rank to each employee based on their salary within their department.
SELECT employee_id, department, salary, RANK() OVER (PARTITION BY [1] ORDER BY salary DESC) AS salary_rank FROM employees;Partitioning by department groups employees so ranks are assigned within each department.
Fix the error in the code to calculate the moving average of sales over the last 3 days.
SELECT date, sales, AVG(sales) OVER (ORDER BY date ROWS BETWEEN [1] PRECEDING AND CURRENT ROW) AS moving_avg FROM sales_data;The window frame should include the current row and the 2 preceding rows to calculate a 3-day moving average.
Fill both blanks to calculate the difference between each sale and the previous sale within each region.
SELECT region, sales, sales - LAG([1]) OVER (PARTITION BY [2] ORDER BY date) AS sales_diff FROM sales_data;
The LAG function should look at the sales column, and partitioning should be done by region to compare sales within the same region.
Fill all three blanks to calculate the cumulative sum of sales per product category ordered by date.
SELECT category, date, sales, SUM([1]) OVER (PARTITION BY [2] ORDER BY [3] ROWS UNBOUNDED PRECEDING) AS cumulative_sales FROM sales_data;
The SUM function should sum the sales column, partitioned by category, and ordered by date to get cumulative sales per category over time.