Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi pals,I need small help. I have a table with data as follows.select * from test_datac1 c2 c3 ----------------------111 4 101122 3 101133 2 102144 2 103155 1 103Now i need to generate a new column c4 as sequence number in the output I need to get the output something as followsc4 c1 c2 c3 -----------------------------1 111 4 1012 122 3 1011 133 2 1021 144 2 1032 155 1 103The newly generated column contains sequence numbers starting from 1 and the sequence should be resetted again to 1 whenever a new c3 value is encountered(for example when the c3 value changes from 101 to 102 the sequence should be resetted to 1).Can anyone help me out on this regard.Thanks in advance,franky
nathans
Aged Yak Warrior
938 Posts
Posted - 2007-11-20 : 18:27:05
try this...
declare @table table (c1 int, c2 int, c3 int)insert into @table select 111, 4, 101 union select 122, 3, 101 union select 133, 2, 102 union select 144, 2, 103 union select 155, 1, 103select row_number() over (partition by c3 order by c3) as [c4], c1, c2, c3from @table
Nathan Skerl
khtan
In (Som, Ni, Yak)
17689 Posts
Posted - 2007-11-20 : 21:06:37
You might want to order by c1 instead of c3
row_number() over (partition by c3 order by c1) as [c4],