I have a transaction table where each entry is a transaction; one of the fields is a date field.
I want to select some info from the transaction table with a WHERE condition, and one of the things I want is the average difference between dates. Effectively I am trying to find the average frequency of transactions meeting my condition, ie
SELECT (average_date_difference) FROM transactions WHERE customerID = xyz;
Where, obviously, (average_date_difference) would be some SQL statement. So my question is, does SQL have a way to select this easily? Or will I need to implement some way to do it programatically? Thanks!
Example:
CustomerID | date
c1 | 25/11/2020
c1 | 21/11/2020
c1 | 18/11/2020
25 - 21 = 4
21 - 18 = 3
(3 + 4) / 2 = 3.5
(average_date_difference) = 3.5 days (expected output)
SELECT avg( datediff(date, lag(date) over (partition by customerID order by date)) )
FROM transactions
WHERE customerID = 'c1';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.