0

I have a table in SQL Server which has 3 fields,

Id int identity(1,1)
thRead int
level int

Now in this table there are threads, like 1-5, all are repeating 5times, like this:

 1,1,1,1,1 2,2,2,2,2 3,3,3,3,3 4,4,4,4,4 5,5,5,5,5

Now I want to update level such that, for a group of records it should increment starting from zero, for another group again from 0 and so on..

I want the output like table below....

1   0
1   1
1   2
1   3
1   4
2   0
2   1
2   2
2   3
2   4
3   0
3   1
3   2
3   3
3   4

Please can anyone help me out with this... the update should be with select query so no need to enter thread manually, it should update automatically

Thanks and Regards Abbas Electricwala

2
  • How exactly the output is relevent to your expected result? Can you explain more? Commented Feb 4, 2011 at 10:30
  • @Anil: actually for any thread added in the forum, its post level increements and when another thread starts the post level is again set to 0, so for any threads the post level should increement, till the thread ends and new thread is start... Commented Feb 4, 2011 at 10:41

2 Answers 2

1

Is this a one off update? If so this would work.

with cte as
(
SELECT Id , thRead, level,
       ROW_NUMBER() OVER (PARTITION BY thRead ORDER BY Id) -1 AS RN
FROM T
)
UPDATE cte
SET level = RN

If you want to do this ongoing for new rows that is more difficult.

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

Comments

0

You can try this

;WITH Temp as
(
 SELECT Id , thRead, ROW_NUMBER() OVER (PARTITION BY thRead ORDER BY Id) -1 'Level' 
 FROM YourTable
)
Select Id, ThRead, Level from Temp

3 Comments

great help man... it worked... thanks a lot anil, but if you can, please explain how does that work out... i didnt understood the logic for it.
@Aabas - Good to know ... The first part in the query is CTS - common table expression. This gives you a temporary set of data which you can use in your main query. Much like table created in FROM Clause. In this CTS I have used ROW_Number() which is SQL in-build function which gives index value to the field you mention in OVER part's PARTITION clause. The result is ordered for each group by ORDER BY clause. Hope this clarifies your idea.
@Aabas - Also, you can mark my answer as accepted answer if it has really solved your problem :)

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.