在sql查询中增加变量

时间:2014-04-07 11:23:16

标签: sql sql-server-2008 tsql

使用SQL Server 2008,我想像这样查询一个表:

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

结果应该是同一个表,并附加一个重要的列。

计数方法是:如果数字在"数字"等于1 - 对于下一个行,将计数器递增1。

提供的表的结果示例:

 | 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

如何实现这一目标?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

这并不难做到。你正在寻找的东西非常类似于总和,你得到的总和和窗口条款。

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

这是一个SQL小提琴:http://sqlfiddle.com/#!4/958e2a/1

答案 2 :(得分:1)

您也可以使用递归选择,但它有点复杂,但如果您插入大于1的其他数字,它可以正常工作:

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