Oracle如何将列转行 列转行oracle方法
oracle列转行
INSERT INTO 新表 (SELECT ID, '呼吸系统疾病' FROM 原表 WHERE 呼吸系统疾病有无 = 1 UNION SELECT ID, '消化系统疾病' FROM 原表 WHERE 消化系统疾病有无 = 1
网站建设哪家好,找成都创新互联!专注于网页设计、网站建设、微信开发、成都微信小程序、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了观山湖免费建站欢迎大家使用!
UNION SELECT ID, '循环系统疾病' FROM 原表 WHERE 循环系统疾病有无 = 1)
如果使用行转列,还得使用merge into,还不如上面的语句清晰。
oracle中怎么将列转换为行
可以使用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
Oracle中列转行,如何实现?
基本思路:对每班学生排序,根据序号构造列名,拼接动态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;
结果如下:
文章标题:Oracle如何将列转行 列转行oracle方法
本文路径:http://ybzwz.com/article/hjhoip.html