Having a hard time getting my head around how to write this query.
I have some data that looks like this:
Now I want to give it a rolling issue number for how many incidents are included with a 7 day time period. The data would look like this:
So I wrote a query that looks like this:
And it works for inventorys that have 2 or less incident strings. In other words, my data comes out like this instead:
The bolded rows are incorrect as they are within 7 days of the last incident, but not resetting to 1. Anyone know why it works for some of the dataset, but not all of it? Anyone have a better way of doing this?
I have some data that looks like this:
Code:
inventory_id incident_timestamp
abc123 4/26/2006 0:00
abc123 7/7/2006 0:00
abc123 7/8/2006 0:00
abc123 7/19/2006 0:00
abc456 4/24/2006 0:00
abc456 7/1/2006 0:00
abc456 7/9/2006 0:00
abc456 7/11/2006 0:00
Now I want to give it a rolling issue number for how many incidents are included with a 7 day time period. The data would look like this:
Code:
inventory_id incident_timestamp Incident_Num
abc123 4/26/2006 0:00 1
abc123 7/7/2006 0:00 1
abc123 7/8/2006 0:00 2
abc123 7/9/2006 0:00 3
abc123 7/10/2006 0:00 4
abc123 7/19/2006 0:00 1
abc123 7/20/2006 0:00 2
abc456 4/24/2006 0:00 1
abc456 7/1/2006 0:00 1
abc456 7/9/2006 0:00 1
abc456 7/11/2006 0:00 2
So I wrote a query that looks like this:
Code:
SELECT a.*
(SELECT COUNT(1) + 1
FROM incident b
WHERE b.inventory_id = a.inventory_id
AND a.incident_timestamp] > b.incident_timestamp]
AND DATEDIFF(dd,b.incident_timestamp] , a.incident_timestamp]) <= 7)
AS IncidentNumber
FROM dbo.incident a
where a.inventory_id = '03DLB'
order by incident_timestamp
And it works for inventorys that have 2 or less incident strings. In other words, my data comes out like this instead:
Code:
inventory_id incident_timestamp Incident_Num
abc123 4/26/2006 0:00 1
abc123 7/7/2006 0:00 1
abc123 7/8/2006 0:00 2
abc123 7/9/2006 0:00 3
abc123 7/10/2006 0:00 4
[b]abc123 7/19/2006 0:00 2
abc123 7/20/2006 0:00 3[/b]
abc456 4/24/2006 0:00 1
abc456 7/1/2006 0:00 1
abc456 7/9/2006 0:00 1
[b]abc456 7/11/2006 0:00 1[/b]
The bolded rows are incorrect as they are within 7 days of the last incident, but not resetting to 1. Anyone know why it works for some of the dataset, but not all of it? Anyone have a better way of doing this?