How do I find the average value of X samples before and after a found event from a sorted table?
In the example below, I have sales_list table. I want to sort the table by date and find the events when sales 'count' goes from less than to greater than 100. Then find the average profit of 2 days before and 2 days after that event.
sales_list
date count profit
12/1/2023 20 100
12/2/2023 50 280
12/3/2023 125 660
12/4/2023 165 850
12/5/2023 85 150
12/6/2023 150 710
12/7/2023 180 740
Expected output:
date count profit avg_prev2 avg_next2
12/3/2023 125 660 190 500
12/6/2023 150 710 500 740
Here, I'm struggling with the AVG(LAG) syntax that doesn't seem correct. I get the: "Windows function may not appear inside an aggregate function".
Any help will be appreciated.
WITH top_sales AS (
SELECT
date,
count,
profit
ROW_NUMBER() OVER (ORDER BY date) AS row_num,
CASE WHEN (
LAG(count) OVER (ORDER BY date) < 100 AND count >= 100)
THEN 1 ELSE 0 END AS high_count
FROM
sales_data
)
SELECT
date,
count,
profit,
AVG(LAG(profit, 2) OVER (ORDER BY date)) AS avg_prev2,
AVG(LEAD(profit, 2) OVER (ORDER BY date)) AS avg_next2
FROM
top_sales
WHERE
high_count = 1
The query below first uses a
cteto associate an incremented row number with each entry. Then, the row numbers are used in aleft joinand two subqueries to search for the desired preceding and proceeding information:See fiddle