I am looking to understand what the average amount of days between transactions is for each of the customers in my database using Snowflake.
SELECT
Customer_ID
, Day_ID
, DATEDIFF(DAY, LAG(Day_ID)
OVER(PARTITION BY Customer_ID
ORDER BY DAY_ID), DAY_ID) AS Time_Since
FROM TABLE
ORDER BY
Customer_ID
, Day_ID
The code above works to get me the time_elapsed but when I try to add an average function I get an error:
SELECT
Customer_ID
AVG(DATEDIFF(DAY, LAG(Day_ID)
OVER(PARTITION BY Customer_ID
ORDER BY DAY_ID), DAY_ID)) AS AVG_Time_Since
FROM TABLE
ORDER BY Customer_ID
GROUP BY Customer_ID
The error reads:
SQL compilation error:
Window function [
LAG(TABLE.DAY_ID)
OVER (PARTITION BY TABLE.CUSTOMER_ID
ORDER BY TABLE.DAY_ID ASC NULLS LAST)
] may not appear inside an aggregate function.
Any ideas?