Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get average time between record creation

So I have data like this:

UserID  CreateDate
1       10/20/2013 4:05
1       10/20/2013 4:10
1       10/21/2013 5:10
2       10/20/2012 4:03

I need to group by each user get the average time between CreateDates. My desired results would be like this:

UserID  AvgTime(minutes)
1       753.5
2       0

How can I find the difference between CreateDates for all records returned for a User grouping?

EDIT:

Using SQL Server 2012

like image 892
RJP Avatar asked Jun 12 '26 01:06

RJP


1 Answers

Try this:

SELECT  A.UserID,
        AVG(CAST(DATEDIFF(MINUTE,B.CreateDate,A.CreateDate) AS FLOAT)) AvgTime
FROM #YourTable A
OUTER APPLY (SELECT TOP 1 *
             FROM #YourTable
             WHERE UserID = A.UserID
             AND CreateDate < A.CreateDate
             ORDER BY CreateDate DESC) B
GROUP BY A.UserID
like image 183
Lamak Avatar answered Jun 15 '26 01:06

Lamak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!