A lot of extra work when it isn't really needed if you ask me.
If OBJECT_ID('tempdb..#Crusty_Table') is not null
Begin
Drop table #Crusty_Table
End
Create table #Crusty_Table (
UniqueIDvarchar(255),
RecordingDatedate
)
Insert Into #Crusty_Table(UniqueID, RecordingDate)
Select '123738','05/21/1969' UNION All
Select '123738','06/09/2010' UNION All
Select '123738','05/29/1967' UNION All
Select '123738','05/29/1967' UNION All
Select '123738','05/31/1967' UNION All
Select '123456','07/09/1977' UNION All
Select '123456','05/29/1967' UNION All
Select '123457','06/09/2010' UNION All
Select '123457','05/21/1969' UNION All
Select '123457','07/09/1977' UNION All
Select '123457','03/07/2007' UNION All
Select '123458','01/15/2014'
Select *
from #Crusty_Table
---------------------------------------------------
---- This is the money shot -----------------------
---------------------------------------------------
select Distinct UniqueID, RecordingDate
--, ROW_NUMBER() over (Partition by UniqueID Order by RecordingDate)
, CASE When (ROW_NUMBER() over (Partition by UniqueID Order by RecordingDate)) = 1 THEN UniqueID
Else UniqueID + '-' + Convert(varchar(255),ROW_NUMBER() over (Partition by UniqueID Order by RecordingDate)-1)
END UniqueID_Alt
From #Crusty_Table
GO
with basedata as (
select
UniqueID,
RecordingDate,
rn = row_number() over (partition by UniqueID order by RecordingDate)
from
#Crusty_Table
)
select
bd.UniqueID,
bd.RecordingDate,
case when bd.rn = 1 then bd.UniqueID else bd.UniqueID + '-' + cast(bd.rn - 1 as varchar) end
from
basedata bd
If OBJECT_ID('tempdb..#Crusty_Table') is not null
Begin
Drop table #Crusty_Table
End
go