簡體   English   中英

SQL查詢中的增量變量

[英]Increment variable in sql query

使用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

如何做到這一點?

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

SQL Fiddle測試

這並不是很難做到的。 您要查找的內容與運行總計非常相似,可以通過sum和windowing子句獲得。

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。

您也可以使用遞歸選擇,但這有點復雜,但是如果您插入其他大於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小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM