Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Partitioning consecutive events

Status
Not open for further replies.

ZenRaven

Programmer
Mar 13, 2007
84
US
Hi all,

I have a table of operator events. OperatorID and EventTime are the important columns. What I want is to return all of the events but to identify groups of consecutive events by operator without cursors or looping.

example (simplified):

OperatorID EventTime
1 10:00
1 11:00
1 12:00
2 14:00
2 15:00
1 16:00
1 17:00
3 18:00

should return

OperatorID EventTime GroupNumber
1 10:00 1
1 11:00 1
1 12:00 1
2 14:00 2
2 15:00 2
1 16:00 3
1 17:00 3
3 18:00 4

I've been messing around with

Code:
SELECT OperatorID, EventTime,
ROW_NUMBER() OVER(PARTITION BY OperatorID ORDER BY EventTime)
from OperatorEvents

which correctly partitions the set but only gives row numbers within each parition. I need something that identifies the partition itself.




--Adam
--"He who knows best knows how little he knows." - Thomas Jefferson
 
;with cte as (select OperatorID, row_number() over (order by OperatorID) as GroupNumber from (select OperatorID from OperatorEvents group by OperatorID) T)

select OE.*, cte.GroupNumber from OperatorEvents OE inner join cte on OP.OperatorID = cte.OperatorID
 
Thanks for the feedback but that doesn't give the required results. With the example I stated it would return all OperatorID 1 records as GroupNumber 1 when in fact there would be 2 different GroupNumbers for OperatorID 1 since OperatorID 2 has a group of events in between.


--Adam
--"He who knows best knows how little he knows." - Thomas Jefferson
 
I understand the problem better now and could not come up to a simple solution from the top of my head - don't have much time to play in SSMS right now.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top