I have a Sql table:
PLAN_CD PLAN_NM CLASS
D01501 DENTAL AA
D01501 DENTAL AB
D01501 DENTAL AC
V01501 VISION AA
V01501 VISION AB
Output should be:
PLAN_CD PLAN_NM
D01501 DENTAL,AA,AB,AC
V01501 VISION,AA,AB
I have a Sql table:
PLAN_CD PLAN_NM CLASS
D01501 DENTAL AA
D01501 DENTAL AB
D01501 DENTAL AC
V01501 VISION AA
V01501 VISION AB
Output should be:
PLAN_CD PLAN_NM
D01501 DENTAL,AA,AB,AC
V01501 VISION,AA,AB
Following 2 Questions might help you:
How to use GROUP BY to concatenate strings in SQL Server?
GROUP BY to combine/concat a column
Have a look.
In MSSQL 2005 and up you can do:
select * into #data
from (
select 'D01501' as PLAN_CD, 'DENTAL' as PLAN_NM, 'AA' as CLASS union
select 'D01501', 'DENTAL', 'AB' union
select 'D01501', 'DENTAL', 'AC' union
select 'V01501', 'VISION', 'AA' union
select 'V01501', 'VISION', 'AB'
) x
select R.PLAN_CD, PLAN_NM = R.PLAN_NM + ',' +
STUFF((
SELECT ',' + [CLASS]
FROM #data
WHERE (PLAN_CD = R.PLAN_CD and PLAN_NM = R.PLAN_NM)
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
,1,1,'')
from
#data R
group by R.PLAN_CD, R.PLAN_NM
This will group on the PLAN_CD and PLAN_NM fields and concatenate the CLASS field as selected with a subquery. Concatenation is done using FOR XML construction.