Another way to do this is by using a cross tab. I used Erikur's data as a starting point. This will be better performance wise because it doesn't have to hit the table more than once.
;WITH CODE_COLS AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY PH.HISTORY_ID ORDER BY (SELECT NULL)) AS PH_RID
,PH.HISTORY_ID
,PH.CODE_ID
, POLICY_DETAILS_ID
FROM @POLHIST PH
)
select ph.POLICY_DETAILS_ID,
ph.HISTORY_ID,
MAX(case when ph.PH_RID = 1 then CODE_ID end) as CODE1,
MAX(case when ph.PH_RID = 2 then CODE_ID end) as CODE2,
MAX(case when ph.PH_RID = 3 then CODE_ID end) as CODE3,
MAX(case when ph.PH_RID = 4 then CODE_ID end) as CODE4,
MAX(case when ph.PH_RID = 5 then CODE_ID end) as CODE5
from CODE_COLS ph
group by ph.POLICY_DETAILS_ID, ph.HISTORY_ID
You can read more about the concept by reading the articles in my signature about cross tabs.
_______________________________________________________________
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/