June 8, 2016 at 9:43 am
Hello, I have a table that I want to add a rownumber to.
I want to partition the row numbers but the PARTITION key word in the ROWNUMBER() function is sort of doing the opposite of what I really want.
I have a table with a "Code" field. The Codes can be repeated but sometimes there is just 1 of them.
So, I would like the results to be like this:
RowNum Code
1 AB10003
2 RG42421
2 RG42421
2 RG42421
3 DG31311
etc...
So, every unique code should get a new row number but if it finds the same code more than once I'd like it to tag the same row number to it.
Is there a clever way to do this?
Thanks!
June 8, 2016 at 9:57 am
You might be over complicating things...is this what you want?
DECLARE @myTable TABLE (Code VARCHAR(7))
INSERT INTO @myTable
VALUES ('AB10003'), ('RG42421'), ('RG42421'), ('RG42421'), ('DG31311')
SELECT DENSE_RANK() OVER (ORDER BY Code) AS RowNum, Code FROM @myTable
June 8, 2016 at 10:50 am
I think yb751 has the right answer. However, maybe you should consider a better name than calling it RowNum. In this case maybe something like CodeNum would be better. It might pedantic but names are very important. I know I would be horribly confused by the name RowNum the way you are using it. But something like CodeNum is immediately clear what it means.
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
June 8, 2016 at 12:30 pm
LOL you're right I was over complicating it... DENSE_RANK worked just peachy.... I admit I didn't know about the dense_rank function ... *blush*
Don't worry, those aren't the actual names of my fields... I was just making that up for the post. 🙂
June 8, 2016 at 12:55 pm
amy26 (6/8/2016)
LOL you're right I was over complicating it... DENSE_RANK worked just peachy.... I admit I didn't know about the dense_rank function ... *blush*Don't worry, those aren't the actual names of my fields... I was just making that up for the post. 🙂
No problem, I'm glad it worked for you.
Cheers,
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply