sql - How to increment column regard on another column value -
i have following data:
(1,'20120615 8:03:43 pm'), (1,'20120615 8:03:43 pm'), (1,'20120615 8:03:48 pm'), (1,'20120615 8:03:53 pm'), (0,'20120615 8:03:58 pm'), (1,'20120615 8:04:03 pm'), (1,'20120615 8:04:08 pm'), (1,'20120615 8:04:13 pm'), (1,'20120615 8:04:18 pm'), (0,'20120615 8:04:23 pm'), (1,'20120615 8:04:28 pm'), (1,'20120615 8:04:33 pm');
my desired result is:
(1,'20120615 8:03:43 pm', 1), (1,'20120615 8:03:43 pm', 1), (1,'20120615 8:03:48 pm', 1), (1,'20120615 8:03:53 pm', 1), (0,'20120615 8:03:58 pm', 0), (1,'20120615 8:04:03 pm', 2), (1,'20120615 8:04:08 pm', 2), (1,'20120615 8:04:13 pm', 2), (1,'20120615 8:04:18 pm', 2), (0,'20120615 8:04:23 pm', 0), (1,'20120615 8:04:28 pm', 3), (1,'20120615 8:04:33 pm', 3);
in words want group data except 0 above order.
here idea. create flag each group starts. 1 - col1
in data above. take cumulative sum of flag. values not 0
, group. following query takes approach, using correlated subqueries computation:
select t.col1, t.dt, (case when t.col1 = 0 0 else 1+grouping end) (select t.*, (select sum(1-col1) t t2 t2.dt <= t.dt ) grouping t ) t;
in sql server 2012, can cumulative sum:
select t.col1, t.dt, (case when col1 = 0 0 else 1+sum(1 - col1) on (order dt) end) t;
Comments
Post a Comment