I believe this will give you the avg days, as requested:
SELECT
Name,
CASE WHEN COUNT(*) = 1 THEN 0 ELSE
(DATEDIFF(DAY, MIN(Date), MAX(Date)) + 1) /
(COUNT(*) - 1) END AS [Average time between incidents(in days)]
FROM your_table_name_goes_here
GROUP BY Name
Thanks a lot Scott !
Very nice approach.
Took me a while to understand your logic..
But that clarified me that I can't use static date range, but rather an incident count.
Can you help me add to the query a condition where only the last X rows\incidents of each person will be calculated in this query ?
DECLARE @number_of_incidents int
SET @number_of_incidents = 3
;WITH cte_incidents AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Date DESC) AS incident_num
FROM your_table_name
)
SELECT
Name,
CASE WHEN COUNT(*) = 1 THEN 0 ELSE
(DATEDIFF(DAY, MIN(Date), MAX(Date)) + 1) /
(COUNT(*) - 1) END AS [Average time between incidents(in days)]
FROM cte_incidents
WHERE incident_num BETWEEN 1 AND @number_of_incidents
GROUP BY Name