PIVOT is clearly what you are looking for, but if you don't mind going DYNAMIC
The source can be a table,temp table, or even SQL as illustrated below. You can also add Group By's and even additional metrics (ie counts and totals).
Declare @SQL varchar(500) = 'Select *,RowNr=Concat(''ICD'',Row_Number() over (Partition By ClaimID Order By ClaimID)) from YourTable'
Exec [prc-Pivot] @SQL,'RowNr','max(CODENUMBER)[]','ClaimID','count(*)[Claims],sum(CODENUMBER)[Total]'
Returns
ClaimID Claims Total ICD1 ICD2 ICD3 ICD4
2 4 1952.80 465.90 238.80 461.90 786.20
The Stored Procedure
CREATE PROCEDURE [dbo].[prc-Pivot] (
@Source varchar(1000), -- Any Table or Select Statement
@PvotCol varchar(250), -- Field name or expression ie. Month(Date)
@Summaries varchar(250), -- aggfunction(aggValue)[optionalTitle]
@GroupBy varchar(250), -- Optional additional Group By
@OtherCols varchar(500) ) -- Optional Group By or aggregates
AS
--Exec [prc-Pivot] 'Select Year=Year(TR_Date),* From [Chinrus-Series].[dbo].[DS_Treasury_Rates]','''Q''+DateName(QQ,TR_Date)','avg(TR_Y10)[-Avg]','Year','count(*)[Records],min(TR_Y10)[Min],max(TR_Y10)[Max],Avg(TR_Y10)[Avg]'
--Exec [prc-Pivot] '#Temp','Attribute','max(Description)[]','ID','count(*)[Records]'
Set NoCount On
Set Ansi_Warnings Off
Declare @Vals varchar(max),@SQL varchar(max);
Set @Vals = ''
Set @OtherCols= IsNull(', ' + @OtherCols,'')
Set @Source = case when @Source Like 'Select%' then @Source else 'Select * From '+@Source end
Create Table #TempPvot (Pvot varchar(100))
Insert Into #TempPvot
Exec ('Select Distinct Convert(varchar(100),' + @PvotCol + ') as Pvot FROM (' + @Source + ') A')
Select @Vals = @Vals + ', isnull(' + Replace(Replace(@Summaries,'(','(CASE WHEN ' + @PvotCol + '=''' + Pvot + ''' THEN '),')[', ' END),0) As [' + Pvot ) From #TempPvot Order by Pvot
Drop Table #TempPvot
Set @SQL = Replace('Select ' + Isnull(@GroupBy,'') + @OtherCols + @Vals + ' From (' + @Source + ') PvtFinal ' + case when Isnull(@GroupBy,'')<>'' then 'Group By ' + @GroupBy + ' Order by ' + @GroupBy else '' end,'Select , ','Select ')
--Print @SQL
Exec (@SQL)
Set NoCount Off
Set Ansi_Warnings on
EDIT: The SQL supplied to the Pivot Procedure should really have a proper sequence. For example, in the Row_Number() ORDER BY should really be a claim date or true sequence.
Select *,RowNr=Concat('ICD',Row_Number() over (Partition By ClaimID Order By ClaimID)) from YourTable
Returns
CLAIMID CODENUMBER RowNr
2 465.90 ICD1
2 238.80 ICD2
2 461.90 ICD3
2 786.20 ICD4