Brightlane's pricing analyst tracks how the average product price changes as products are added to the catalog in sequence by id.
Write a query to return the ID, name, and price of every product, plus the running average price accumulated from the first product through that product in order of id.
Assumptions:
- The
productstable has one row per product with anid, aname, and aprice. - Products are reviewed in ascending
idorder. The running average at each row is the average ofpriceacross every product whoseidis less than or equal to that row'sid.
Output:
- One row per product, with columns
id,name,price, andrunning_avg_price.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
id,
name,
price,
AVG(price) OVER (
ORDER BY
id
) AS running_avg_price
FROM
products The shape
AVG(price) OVER (ORDER BY id) recomputes the mean as each product enters the catalog in id order. Where a plain AVG(price) would return one number for the whole table, the windowed form attaches a fresh average to every row, computed from every product seen so far.
Clause by clause
SELECT id, name, pricereturns each product's identifier, name, and price unchanged. The running average is added alongside; the rows are preserved.AVG(price) OVER (ORDER BY id) AS running_avg_priceaveragespriceacross every row from the first product through the current one. TheORDER BY idinsideOVERdefines that growing set. On the first row, the average is the single price itself,999. On the second row, the average is over two prices,(999 + 1199) / 2 = 1099. As more rows enter the running set, the average shifts toward the overall catalog mean.FROM productsreads every product. Every row in the catalog contributes once it enters the running set.
You practiced AVG(...) OVER (ORDER BY ...) — running average; the value updates as the cumulative set grows row by row.