1. 程式人生 > >Oracle 合併行,合併列

Oracle 合併行,合併列

表(TBStudent)結構及資料如下:
姓名 科目 成績
張三 語文 90
張三 數學 80
張三 英語 100
現在要將表變成如下格式:
姓名 各科成績
張三 語文:90,數學:80,英語:100

select studentname,TRANSLATE(LTRIM (text, '/'), '*/', '*,')各科成績 from 
(SELECT ROW_NUMBER () OVER (PARTITION BY studentname ORDER BY studentname,lvl DESC)rn,studentname,text 
FROM (SELECT studentname, LEVEL lvl, 
SYS_CONNECT_BY_PATH (各科成績,'/') text 
FROM (SELECT studentname, (subject||':'||subjectscore) as 各科成績, 
ROW_NUMBER () OVER (PARTITION BY studentname ORDER BY studentname) x 
FROM TBStudent
group by studentname,subject,subjectscore
ORDER BY studentname) a 
CONNECT BY studentname= PRIOR studentname AND x - 1 = PRIOR x)) 
WHERE rn = 1 
ORDER BY studentname; 

當然也可以寫函式來實現合併行或者列,請各位多多指教。