Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Grouping sequential rows based on a certain criteria

$
0
0

I need some advice on how to handle putting sequential rows in groups based on a certain criteria. I have some rows in a tables structured like this. I have a row number (ordered and sequential), start and end timestamps, and duration which is just the difference between the timestamps in seconds. What I would like to do is add a column called Group that contains the group number for the row. The group will change when the duration is 60 seconds or greater. So for example in these rows below the group would be "1" for rows 1 to 138, then it would be "2" for rows 139 through the next time the duration is 60 or greater.

Is the best way to handle this iterating through rows and comparing duration to 60 and assigning the group number there? Or does someone see a set approach somewhere that I could use. I'm using SQL 2008 R2. Thanks in advance for any help

rownum StartTime EndTime Duration
1 2013-04-05 09:15:05.000 2013-04-05 09:15:35.000 30
2 2013-04-05 09:15:35.000 2013-04-05 09:16:05.000 30
3 2013-04-05 09:16:05.000 2013-04-05 09:16:35.000 30
4 2013-04-05 09:16:35.000 2013-04-05 09:17:11.000 36
5 2013-04-05 09:17:11.000 2013-04-05 09:17:35.000 24
6 2013-04-05 09:17:35.000 2013-04-05 09:18:05.000 30
7 2013-04-05 09:18:05.000 2013-04-05 09:18:35.000 30

...
137 2013-04-05 10:23:06.000 2013-04-05 10:23:35.000 29
138 2013-04-05 10:23:35.000 2013-04-05 10:24:07.000 32
139 2013-04-05 10:24:07.000 2013-04-05 10:25:07.000 60
140 2013-04-05 10:25:07.000 2013-04-05 10:25:36.000 29
141 2013-04-05 10:25:36.000 2013-04-05 10:26:08.000 32
142 2013-04-05 10:26:08.000 2013-04-05 10:26:36.000 28
143 2013-04-05 10:26:36.000 2013-04-05 10:27:06.000 30


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>