十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
INSERT INTO 新表 (SELECT ID, '呼吸系统疾病' FROM 原表 WHERE 呼吸系统疾病有无 = 1 UNION SELECT ID, '消化系统疾病' FROM 原表 WHERE 消化系统疾病有无 = 1
创新互联专业为企业提供鄂温克网站建设、鄂温克做网站、鄂温克网站设计、鄂温克网站制作等企业网站建设、网页设计与制作、鄂温克企业网站模板建站服务,十多年鄂温克做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
UNION SELECT ID, '循环系统疾病' FROM 原表 WHERE 循环系统疾病有无 = 1)
如果使用行转列,还得使用merge into,还不如上面的语句清晰。
可以使用wm_concat()函数;
下面是我做的一个例子,可以参考下,当然具体语法可以百度,也可以去官方文档查:
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
基本思路:对每班学生排序,根据序号构造列名,拼接动态sql
--测试数据
create table
("学生" varchar2(10)
,"学号" 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
--动态拼接Pivot
declare
sqlstr varchar2(8000):='';
begin
--构造类似于 '学号1','学号2',... 的字符串
for x in (
select distinct row_number() over (partition by "班级" order by "学号") seq
from "表A" order by seq ) loop
sqlstr := sqlstr || ',''' || '学号' ||to_char(x.seq)||'''';
end loop;
sqlstr:=substr(sqlstr,2,length(sqlstr)-1);
--将前面构造的字符串放入Pivot语句中
sqlstr:='
select * from (
select "学号","班级", ''学号''|| to_char(
row_number() over (partition by "班级" order by "学号")) seq
from "表A") t
pivot(
max("学号")
for seq in ('||sqlstr||')
)';
--dbms_output.put_line(sqlstr);
--将查询结果放入临时视图中
sqlstr := 'CREATE OR REPLACE VIEW tmp_result AS '|| sqlstr;
--dbms_output.put_line(sqlstr);
execute immediate sqlstr;
end;
--查看结果
select * from tmp_result;
结果如下: