Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 enumerating row number

Author  Topic 

slimt_slimt
Aged Yak Warrior

746 Posts

Posted - 2013-01-10 : 07:46:17
Hi,

I have two columns c1 and c2:

c1 c2
1 1
2 0
3 0
4 1
5 1
6 0
7 0
8 0
9 0
10 1
11 0
12 0

what i want is to get column c3 which will enumerate each part of "pairs" between 1 and next 1.
so result for C3:


c1 c2 c3
1 1 1
2 0 2
3 0 3
4 1 1
5 1 1
6 0 2
7 0 3
8 0 4
9 0 5
10 1 1
11 0 2
12 0 3

thank you

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2013-01-10 : 09:56:22
See if this will work for you
SELECT
t.c1,t.c2,t.c1-(t2.n-1) AS c3
FROM
Tbl t
CROSS APPLY
(
SELECT MAX(c1) AS n FROM Tbl t2
WHERE t2.c1 <= t.c1 AND t2.c2 = 1
) t2;
Go to Top of Page
   

- Advertisement -