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 2008 Forums
 Transact-SQL (2008)
 Add Sequence Number within group

Author  Topic 

scabral7
Yak Posting Veteran

57 Posts

Posted - 2013-10-13 : 20:52:02
Hi,

I have the following data:

POL# POL_EFF_DATE
123 1-1-2012
123 1-1-2012
123 1-1-2012
123 1-1-2013
123 1-1-2013
456 1-1-2012
456 1-1-2012
456 1-1-2013
456 1-1-2013

I want to add sequence number to each group with same Pol# and Effective Date like this:

POL# POL_EFF_DATE Seq
123 1-1-2012 1
123 1-1-2012 1
123 1-1-2012 1
123 1-1-2013 2
123 1-1-2013 2
456 1-1-2012 1
456 1-1-2012 1
456 1-1-2013 2
456 1-1-2013 2

is there a set based function to accomplish this in SQL 2008?

thanks
Scott

VeeranjaneyuluAnnapureddy
Posting Yak Master

169 Posts

Posted - 2013-10-14 : 01:07:11
Declare @Table Table (POL# int,POL_EFF_DATE varchar(20))

insert @Table
Select 123,'1-1-2012'
union all Select 123,'1-1-2012'
union all Select 123,'1-1-2012'
union all Select 123,'1-1-2013'
union all Select 123,'1-1-2013'
union all Select 456,'1-1-2012'
union all Select 456,'1-1-2012'
union all Select 456,'1-1-2013'
union all Select 456,'1-1-2013'

Select *,Dense_Rank() Over (Partition By POL_EFF_DATE Order by POL#) AS Seq From @Table


veeranjaneyulu
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-10-14 : 01:54:21
it should be

Select *,Dense_Rank() Over (Partition By [POL#] Order by POL_EFF_DATE) AS Seq From @Table


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

scabral7
Yak Posting Veteran

57 Posts

Posted - 2013-10-14 : 12:42:40
thanks visakh16,

that worked!
Go to Top of Page
   

- Advertisement -