INSERT INTO 新表 (SELECT ID, '呼吸系統(tǒng)疾病' FROM 原表 WHERE 呼吸系統(tǒng)疾病有無 = 1 UNION SELECT ID, '消化系統(tǒng)疾病' FROM 原表 WHERE 消化系統(tǒng)疾病有無 = 1
網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、成都微信小程序、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了觀山湖免費(fèi)建站歡迎大家使用!
UNION SELECT ID, '循環(huán)系統(tǒng)疾病' FROM 原表 WHERE 循環(huán)系統(tǒng)疾病有無 = 1)
如果使用行轉(zhuǎn)列,還得使用merge into,還不如上面的語句清晰。
可以使用wm_concat()函數(shù);
下面是我做的一個例子,可以參考下,當(dāng)然具體語法可以百度,也可以去官方文檔查:
SCOTT@ ysdb1show user
USER is "SCOTT"
SCOTT@ ysdb1create table test_concat(id number(5),name varchar2(10));
Table created.
SCOTT@ ysdb1insert into test_concat values(1,'a');
1 row created.
SCOTT@ ysdb1insert into test_concat values(1,'b');
1 row created.
SCOTT@ ysdb1insert into test_concat values(1,'c');
1 row created.
SCOTT@ ysdb1insert into test_concat values(2,'q');
1 row created.
SCOTT@ ysdb1insert into test_concat values(2,'w');
1 row created.
SCOTT@ ysdb1insert into test_concat values(2,'e');
1 row created.
SCOTT@ ysdb1insert into test_concat values(2,'f');
1 row created.
SCOTT@ ysdb1select * from test_concat;
ID NAME
---------- ----------
1 a
1 b
1 c
2 q
2 w
2 e
2 f
7 rows selected.
SCOTT@ ysdb1select wm_concat(name) from test_concat;
WM_CONCAT(NAME)
--------------------------------------------------------------------------------
a,b,c,q,w,e,f
SCOTT@ ysdb1select id,wm_concat(name) from test_concat group by id;
ID WM_CONCAT(NAME)
---------- --------------------------------------------------------------------------------
1 a,c,b
2 q,f,e,w
基本思路:對每班學(xué)生排序,根據(jù)序號構(gòu)造列名,拼接動態(tài)sql
--測試數(shù)據(jù)
create?table
("學(xué)生"?varchar2(10)
,"學(xué)號"?varchar2(10)
,"班級"?varchar2(10)
);?
insert?into?"表A"?
select?'張三','100','一班'?from?dual?union?all
select?'李四','101','二班'?from?dual?union?all
select?'王五','102','一班'?from?dual?union?all
select?'趙六','103','三班'?from?dual?union?all
select?'李二','104','二班'?from?dual
--動態(tài)拼接Pivot??
declare
sqlstr?varchar2(8000):='';
begin
--構(gòu)造類似于?'學(xué)號1','學(xué)號2',...??的字符串
for?x?in?(?????
select?distinct?row_number()?over?(partition?by?"班級"?order?by?"學(xué)號")?seq?
from?"表A"?order?by?seq?)?loop?
sqlstr?:=?sqlstr?||?','''?||?'學(xué)號'?||to_char(x.seq)||'''';?
end?loop;?
sqlstr:=substr(sqlstr,2,length(sqlstr)-1);
--將前面構(gòu)造的字符串放入Pivot語句中
sqlstr:='
select?*?from?(
select?"學(xué)號","班級",?''學(xué)號''||?to_char(
row_number()?over?(partition?by?"班級"?order?by?"學(xué)號"))?seq??
from?"表A")?t
pivot(
max("學(xué)號")
for?seq?in?('||sqlstr||')??
)';
--dbms_output.put_line(sqlstr);
--將查詢結(jié)果放入臨時視圖中
sqlstr?:=?'CREATE?OR?REPLACE?VIEW?tmp_result??AS?'||?sqlstr;
--dbms_output.put_line(sqlstr);
execute?immediate?sqlstr;
end;
--查看結(jié)果
select?*?from?tmp_result;
結(jié)果如下: