Window Function for Moving Average
Beginner Mode

Objective

Given a table sales with columns sale_date (in YYYY-MM-DD format) and amount, write an SQL query to compute the 7-day moving average of amount for each sale_date. The moving average should include the current day and the six preceding days. Round the moving average to two decimal places.

Additional information

  • The output should include the columns sale_date, amount, and moving_average.
  • Order the results by sale_date in ascending order.
  • Utilize appropriate SQL window functions to efficiently calculate the moving average.
  • Assume that there are no duplicate sale_date entries and that sale_date values are consecutive without gaps.

Examples

Example 1:

Input:

sales
amountsale_date
1002023-01-01
1502023-01-02
2002023-01-03
1202023-01-04
1802023-01-05
1602023-01-06
1402023-01-07
1902023-01-08
1702023-01-09

Output:
amountmoving_averagesale_date
1001002023-01-01
1501252023-01-02
2001502023-01-03
120142.52023-01-04
1801502023-01-05
160151.672023-01-06
1401502023-01-07
190162.862023-01-08
170165.712023-01-09
Quick Solution

Code Environment

Sign in or try as guest to run your code.

Sign In

Track

Question Difficulty Company Access
Need more practice in this area? Explore more questions →