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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Running count of non unique rows

Author  Topic 

Humate
Posting Yak Master

101 Posts

Posted - 2008-01-15 : 08:53:46
Hi all,

I have been struggling with this query. I want to create a column that has a running count of how many times a reference number is populated in the results of my query. For instance:

Reference---------------Counter

1234 ---------------------- 1
1234 ---------------------- 2
1234 ---------------------- 3
4321 ---------------------- 1
2341 ---------------------- 1
2341 ---------------------- 2



Any help much appreciated.

Humate

harsh_athalye
Master Smack Fu Yak Hacker

5581 Posts

Posted - 2008-01-15 : 09:06:42
Make use RANK() function.

Harsh Athalye
India.
"The IMPOSSIBLE is often UNTRIED"
Go to Top of Page

rohitkumar
Constraint Violating Yak Guru

472 Posts

Posted - 2008-01-15 : 09:10:42
read about "PARTITION BY" and "ROW_NUMBER()"

example here
http://www.4guysfromrolla.com/webtech/010406-1.shtml#postadlink
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-01-15 : 09:14:19
SELECT ROW_NUMBER() OVER (PARTITION BY Reference ORDER BY PK )AS Counter,*
FROM Table


pk is your primary key
Go to Top of Page

Humate
Posting Yak Master

101 Posts

Posted - 2008-01-15 : 11:27:08
Excellent, thanks all!

I have used Row_number () and Partition by before, but I couldn't remember how to do this at all!
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-01-16 : 02:09:34
See what you can do with Row_number()
http://sqlblogcasts.com/blogs/madhivanan/archive/2007/08/27/multipurpose-row-number-function.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -