-1
我有一個SQL表輸出:需要在SQL查詢
PLAN_CD PLAN_NM CLASS
D01501 DENTAL AA
D01501 DENTAL AB
D01501 DENTAL AC
V01501 VISION AA
V01501 VISION AB
輸出應該是:
PLAN_CD PLAN_NM
D01501 DENTAL,AA,AB,AC
V01501 VISION,AA,AB
我有一個SQL表輸出:需要在SQL查詢
PLAN_CD PLAN_NM CLASS
D01501 DENTAL AA
D01501 DENTAL AB
D01501 DENTAL AC
V01501 VISION AA
V01501 VISION AB
輸出應該是:
PLAN_CD PLAN_NM
D01501 DENTAL,AA,AB,AC
V01501 VISION,AA,AB
在MSSQL 2005和最多可以這樣做:
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
這將組對PLAN_CD和PLAN_NM領域,與子查詢選擇拼接CLASS域。連接使用FOR XML結構完成。
問題是? –
你不需要「輸出」。你需要做一些編碼。 –