0

I am facing one issue in below query

CREATE TABLE #tmp(rowid int,settle_id int)
insert into #tmp
select top 100 
case when row_number() over (order by settle_id) > 10 then row_number() over (order by settle_id) - 10 else row_number() over (order by settle_id) end as rowid,settle_id from student_id(nolock) 
select * from #tmp
drop table #tmp 

I want row id should start from 1 -> 10 everytime but for first two sets it start from 1->10 but there after it starts with 11. Please let me know what i am missing.

2
  • You should tag your question with the database you are using. Commented Nov 5, 2014 at 11:24
  • Added sql-server tag based on the #tmp and top 100 syntax Commented Nov 5, 2014 at 11:25

2 Answers 2

1

Use the below query to get the expected result.

SELECT 
CASE WHEN ((row_number() over(order by settle_id) % 10) = 0) 
     THEN 10 
     ELSE (row_number() over (ORDER BY settle_id) % 10)  
END AS  RowID, settle_id
FROM student
Sign up to request clarification or add additional context in comments.

Comments

1

Try using modulo arithmetic:

select ((row_number() over (order by settle_id) - 1) % 10) + 1 as rowid, settle_id
from student;

Some databases use the mod() function instead of %.

3 Comments

Above query start the rowid from 2 only.
so use -1 instead of +1 - apply some basic mathematics!!
@Veera . . . row_number() starts at 1, but modulo starts returning at 0. The solution is to subtract 1 and then add it back in.

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.