Oracle 合併行,合併列
阿新 • • 發佈:2019-02-05
表(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;
當然也可以寫函式來實現合併行或者列,請各位多多指教。