oracle數(shù)據(jù)多行不同列進(jìn)行合并顯示
10年積累的網(wǎng)站設(shè)計(jì)制作、網(wǎng)站建設(shè)經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問(wèn)題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先網(wǎng)站制作后付款的網(wǎng)站建設(shè)流程,更有青州免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
select id ,listagg( name, ',' ) within group ( order by id ) as name from TABLE_NAME GROUP BY id;
方法有如下兩種:
1、利用存儲(chǔ)過(guò)程,先查出所要的數(shù)據(jù),循環(huán)放入一列中:
select 編碼,decode(一級(jí),null,null,一級(jí)||'')||decode(二級(jí),null,null,二級(jí)||'')||decode(三級(jí),null,null,三級(jí)||'')||decode(四級(jí),null,null,四級(jí)||'') from 表名
2、使用wm_concat()方法,如select wm_concat(name) as name from user;
select name,
max(case when course = '語(yǔ)文' then course else null end) course1,
max(case when course = '語(yǔ)文' then score else null end) score1,
max(case when course = '數(shù)學(xué)' then course else null end) course2,
max(case when course = '數(shù)學(xué)' then score else null end) score2,
max(case when course = '英語(yǔ)' then course else null end) course3,
max(case when course = '英語(yǔ)' then score else null end) score3
from table
group by name
原表名字:test
三個(gè)字段:姓名:nm,選修課:xx,成績(jī):cj
分兩張情況:
一、選修科目數(shù)量確定為2:
兩種寫(xiě)法:
1、普通寫(xiě)法
with?t?as
(select?nm,
'選修'?||?row_number()?over(partition?by?nm?order?by?cj)?xx_tp,
'成績(jī)'?||?row_number()?over(partition?by?nm?order?by?cj)?cj_tp,
xx,
cj
from?test?a)
select?nm?"姓名",
max(decode(xx_tp,?'選修1',?xx,?null))?"選修1",
max(decode(cj_tp,?'成績(jī)1',?cj,?null))?"成績(jī)1",
max(decode(xx_tp,?'選修2',?xx,?null))?"選修2",
max(decode(cj_tp,?'成績(jī)2',?cj,?null))?"成績(jī)2"
from?t
group?by?nm
2、pivot
with?t?as
(select?nm,
'選修'?||?row_number()?over(partition?by?nm?order?by?cj)?xx_tp,
'成績(jī)'?||?row_number()?over(partition?by?nm?order?by?cj)?cj_tp,
xx,
cj
from?test?a)
select?nm?"姓名",?max(xx1)?"選修1",?max(cj1)?"成績(jī)1",?max(xx2)?"選修2",?max(cj2)?"成績(jī)2"
from?(select?*
from?t
pivot(max(xx)
for?xx_tp?in('選修1'?xx1,?'選修2'?xx2)))?a
pivot?(max(cj)?for?cj_tp?in('成績(jī)1'?cj1,?'成績(jī)2'?cj2))
group?by?nm
二、選修科目數(shù)量不確定
首先去?;tid=1609939extra=highlight=%B6%AF%CC%AC%D0%D0%D7%AA%C1%D0page=1 ? 復(fù)制動(dòng)態(tài)行轉(zhuǎn)列的代碼到sql窗口中運(yùn)行,然后執(zhí)行如下代碼:
with?t?as
(select?*
from?table(pivot('select?nm,
''成績(jī)''?||?row_number()?over(partition?by?nm?order?by?cj)?cj_tp,
cj
from?test?a'))),
t1?as
(select?*
from?table(pivot('select?nm,
''選修''?||?row_number()?over(partition?by?nm?order?by?cj)?cj_tp,
xx
from?test?a')))
select?*?from?t,?t1?where?t.nm?=?t1.nm
以上。