0

Using SQL Server 2008, I want to query a table like so:

 | ID | Number 
 -------------
 |  1 |   0    
 |  2 |   0    
 |  3 |   1    
 |  4 |   0    
 |  5 |   0    
 |  6 |   1    
 |  7 |   1    
 |  8 |   1  

The result should be the same table with an additional column that counts.

The method of counting is: if the number in "number" equals to 1 - increment the counter by one for the next line.

An example of result for the provided table:

 | ID | Number | Counter
 -----------------------
 |  1 |   0    |    1
 |  2 |   0    |    1
 |  3 |   1    |    1
 |  4 |   0    |    2
 |  5 |   0    |    2
 |  6 |   1    |    2
 |  7 |   1    |    3
 |  8 |   1    |    4

How can this be achieved?

3
  • 1
    Which RDBMS are you use? Commented Apr 7, 2014 at 11:25
  • Any way to achieve this without sub-queries? Commented Apr 7, 2014 at 11:59
  • I think that if you work on MySQL it is possible to do it with out subquery but in Sql Server i don't think so. Commented Apr 7, 2014 at 12:03

3 Answers 3

3
select [ID], [Number],
       isnull(1+(select sum([Number]) from Table1 t2 where t2.ID<t1.Id),1)
from Table1 t1

SQL Fiddle to test

Sign up to request clarification or add additional context in comments.

Comments

1

This is not too hard to do. What you are looking for is very much like the running total, which you get with sum and a windowing clause.

select id, num, 1 + sum(num) over (order by id) - num as counter
from mytable
order by id;

Here is an SQL fiddle: http://sqlfiddle.com/#!4/958e2a/1.

5 Comments

OP is using SQL Server
Is it faster then Luv's answer?
@Luv: The request was only tagged "sql" at first. Anyhow, SQL Server does support window functions. So it only depends on the version wether above query works or not.
@Itzik Gili: It should be faster. Ideally the table is read just once, which is likely to happen with SUM OVER. In Luv's statement the table must be read again and again.
Just checked it. SUM OVER is supported in SQL Server 2012, but not in SQL Server 2008.
1

You can use recursive select too but it is a bit complicated but if you insert other numbers which are greater than 1 it work fine:

with tab(id,number,counter,rn) as
(select t.*,1 as counter,1 as rn from table1 t where id = 1
union all
select t.*,case when t.number = 1 then counter + 1 else counter end as counter,
rn + 1 as rn from table1 t,tab where t.id = tab.rn + 1),
tab2 as (select id,number,counter from tab)
select id,number,case when number = 1 then counter - 1 
else counter end as counter from tab2;

SQL Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.