I have this kind of situation -
Column A
1
0
0
0
1
0
0
0
0
1
0
1
0
0
1
0
I want something like this-
Column A Column B
1 1
0 1
0 1
0 1
1 2
0 2
0 2
0 2
0 2
1 3
0 3
1 4
0 4
0 4
1 5
0 5
Its like for each occurance of 1 in column A we are increasing the number in column B by one. I want to have this in a select. I can't use loop for this.
I am using SQL-Server 2008 R2. Can anyone please give me idea how it can done. Thanks in advance.
You'll need something to order by. Assuming you have an ID:
Result:
edit: The above is only available from sql server 2012, for previous editions the following should work:
Result:
First, you cannot do what you want, because your result depends on the ordering of the rows in the table. Remember: SQL tables represent unordered sets; there is no ordering unless a column makes that explicit.
If you have an ordering column, then think the simplest method in SQL Server 2008 is a correlated subquery or
outer apply
:With a cte and window function Row_Number()... However, I should note that it would be best if you replace (Select NULL) in the OVER clause with a proper sequence (ie identity int, datetime).
Returns