Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

SQL Server: increment row number only one value

I have this table:

Id status
-----------
1   true
2   false
3   true
4   true
5   false

I need output like this:

Id status  count
-----------------
1   true    1
2   false   1
3   true    2
4   true    3
5   false   3

So I need to increment only true and but not false

question from:https://stackoverflow.com/questions/65856687/sql-server-increment-row-number-only-one-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the window functions ( well worth your time to get familiar with)

Example

Declare @YourTable Table ([Id] int,[status] varchar(50))  Insert Into @YourTable Values 
 (1,'true')
,(2,'false')
,(3,'true')
,(4,'true')
,(5,'false')
 
Select *
      ,count = sum(case when status='true' then 1 else 0 end) over (order by id) 
 From @YourTable

Returns

Id  status  count
1   true    1
2   false   1
3   true    2
4   true    3
5   false   3

Edit... If [status] is a bit

...
,count = sum(convert(int,status)) over (order by id) 
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...