pivot和unpivot
Posted jiangqingfeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pivot和unpivot相关的知识,希望对你有一定的参考价值。
--pivot 列转行
drop table cs_thz_1;
create table cs_thz_1(sid number(10),sname varchar2(1000),snum number(10));
insert into cs_thz_1(sid,sname,snum)
select 1 as sid,‘苹果‘ sname,1000 as snum from dual union all
select 2 as sid,‘苹果‘ sname,2000 as snum from dual union all
select 3 as sid,‘苹果‘ sname,4000 as snum from dual union all
select 4 as sid,‘橘子‘ sname,5000 as snum from dual union all
select 5 as sid,‘橘子‘ sname,3000 as snum from dual union all
select 6 as sid,‘葡萄‘ sname,3500 as snum from dual union all
select 7 as sid,‘芒果‘ sname,4200 as snum from dual union all
select 8 as sid,‘芒果‘ sname,5500 as snum from dual
;
select * from (select sname,snum from cs_thz_1) pivot (sum(snum) for sname in (‘苹果‘ as 苹果,‘橘子‘ as 橘子,‘葡萄‘ as 葡萄,‘芒果‘ as 芒果))
;
-----pivot
drop table cs_thz_2;
create table cs_thz_2(sid number(10),sname varchar2(1000),snum number(10));
insert into cs_thz_2(sid,sname,snum)
select 5 as sid,‘苹果‘ sname,1000 as snum from dual union all
select 5 as sid,‘苹果‘ sname,2000 as snum from dual union all
select 5 as sid,‘苹果‘ sname,4000 as snum from dual union all
select 5 as sid,‘橘子‘ sname,5000 as snum from dual union all
select 6 as sid,‘橘子‘ sname,3000 as snum from dual union all
select 6 as sid,‘葡萄‘ sname,3500 as snum from dual union all
select 6 as sid,‘芒果‘ sname,4200 as snum from dual union all
select 6 as sid,‘芒果‘ sname,5500 as snum from dual
;
select * from cs_thz_2 pivot (sum(snum) for sname in (‘苹果‘ as 苹果,‘橘子‘ as 橘子,‘葡萄‘ as 葡萄,‘芒果‘ as 芒果) )
;
--pivot(聚合函数 for 列名 in (类型)),其中 in (‘‘) 中可以指定列名,还可以指定子查询,比如 select distinct code from tab
--pivot(任一聚合函数 for 需转为列的值所在列名 in (需转为列名的值))
--unpivot(新增值所在列的列名 for 新增列转为行后所在列的列名 in (需转为行的列名))
--unpivot行转列
drop table cs_thz_3;
create table cs_thz_3(sid number(10),sname varchar2(1000),q1 number(10),q2 number(10),q3 number(10),q4 number(10));
insert into cs_thz_3(sid,sname,q1,q2,q3,q4)
select 1 sid,‘苹果‘ sname,1000 q1,2000 q2,3300 q3,5000 q4 from dual union all
select 2 sid,‘橘子‘ sname,3000 q1,3000 q2,3200 q3,1500 q4 from dual union all
select 3 sid,‘香蕉‘ sname,2500 q1,3500 q2,2200 q3,2500 q4 from dual union all
select 4 sid,‘葡萄‘ sname,1500 q1,2500 q2,1200 q3,3500 q4 from dual;
commit;
select sid,sname,jidu,xiaoshou from cs_thz_3 unpivot (xiaoshou for jidu in (q1,q2,q3,q4));
以上是关于pivot和unpivot的主要内容,如果未能解决你的问题,请参考以下文章