SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Increment number on fields with the same value.
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

saloom
Starting Member

3 Posts

Posted - 12/02/2013 :  15:18:58  Show Profile  Reply with Quote
Hallo people! I am very new to SQL and I need to do something that I've been searching and searching and can't seem to find a solution. I have a Column named 'Series' and a column named 'Linenumber'. They look like this:

Series Linenumber
234 NULL
234 NULL
235 NULL
235 NULL
234 NULL
234 NULL
235 NULL
235 NULL
236 NULL
236 NULL
236 NULL

and I want to run a query and make it look like this:


Series Linenumber
234 1
234 2
235 1
235 2
234 3
234 4
235 3
235 4
236 1
236 2
236 3

So basically I want Linenumber to be an increment column but to increment seperately for each value of Series. RDBMS is Microsoft SQL Server 2008.

Do I ask too much???

TG
Flowing Fount of Yak Knowledge

USA
6062 Posts

Posted - 12/02/2013 :  15:26:20  Show Profile  Reply with Quote
This statement will simply ouput the results as you described. It won't change the data in the table. Is that what you want?

select Series
       , row_number() over (partition by series order by lineNumber) as LineNumber
from   yourTable


Be One with the Optimizer
TG
Go to Top of Page

saloom
Starting Member

3 Posts

Posted - 12/02/2013 :  15:29:38  Show Profile  Reply with Quote
Yes I want to change the "NULL'S" into numbers. Using something like an UPDATE query.
Go to Top of Page

TG
Flowing Fount of Yak Knowledge

USA
6062 Posts

Posted - 12/02/2013 :  15:39:57  Show Profile  Reply with Quote
In order to do that there must be something in your table that uniquely identifies a row. If there is no way to distinguish one row that has a [Series] = 234 from a different row that has [Series]=234 then you have do something like this:


alter table yourTable add i int identity(1,1)
go

update t set
       t.lineNumber = d.lineNumber
from   (
       select i
              ,Series
              , row_number() over (partition by series order by lineNumber) as LineNumber
       from   yourTable
       ) d
inner join yourTable t
       on t.i = d.i

go
alter table #yourTable drop column i


EDIT:
fixed syntax error

Be One with the Optimizer
TG

Edited by - TG on 12/02/2013 15:43:57
Go to Top of Page

saloom
Starting Member

3 Posts

Posted - 12/02/2013 :  16:41:55  Show Profile  Reply with Quote
Aaaaww this works wonders!! This is magic!! Thanks a million!! :)
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.09 seconds. Powered By: Snitz Forums 2000