Complete the code to calculate a running total of sales ordered by date using ROWS BETWEEN.
SELECT date, sales, SUM(sales) OVER (ORDER BY date [1] UNBOUNDED PRECEDING) AS running_total FROM sales_data;The ROWS keyword specifies the window frame in terms of physical rows, which is suitable for running totals ordered by date.
Complete the code to calculate the average sales over the current row and the two preceding rows using ROWS BETWEEN.
SELECT date, sales, AVG(sales) OVER (ORDER BY date [1] 2 PRECEDING AND CURRENT ROW) AS avg_sales FROM sales_data;
The ROWS BETWEEN clause defines the window frame as the current row and two rows before it, which is needed for this moving average.
Fix the error in the window frame clause to correctly calculate the sum over the last 7 days using RANGE BETWEEN.
SELECT date, sales, SUM(sales) OVER (ORDER BY date [1] INTERVAL '7 days' PRECEDING AND CURRENT ROW) AS weekly_sum FROM sales_data;
The RANGE BETWEEN clause is used with intervals like '7 days' to define a frame based on value ranges, suitable for date intervals.
Fill both blanks to calculate the cumulative sum of sales partitioned by region and ordered by date using ROWS BETWEEN.
SELECT region, date, sales, SUM(sales) OVER (PARTITION BY region ORDER BY date [1] BETWEEN UNBOUNDED PRECEDING [2] CURRENT ROW) AS cum_sum FROM sales_data;
The window frame uses ROWS to specify physical rows and AND to separate the frame boundaries.
Fill all three blanks to calculate the moving average of sales over the current row and the previous 3 days using RANGE BETWEEN.
SELECT date, sales, AVG(sales) OVER (ORDER BY date [1] BETWEEN INTERVAL '3 days' PRECEDING [2] [3]) AS moving_avg FROM sales_data;
The window frame uses RANGE to specify value-based framing, AND to separate boundaries, and CURRENT ROW as the upper boundary.