create table A(名称 varchar2(10),"1月" varchar2(10),"2月" varchar2(10),"3月" varchar2(10),"4月" varchar2(10))
成都创新互联是一家专业提供兴安盟乌兰浩特企业网站建设,专注与成都做网站、网站制作、H5技术、小程序制作等业务。10年已为兴安盟乌兰浩特众多企业、政府机构等服务。创新互联专业网站制作公司优惠进行中。
insert into A values ('土豆',50,60,70,80);
insert into A values ('白菜',150,160,170,180);
commit;
select * from A;
select * from (
select 名称,'1月' 月份,"1月" 值 from A
union all
select 名称,'2月' 月份,"2月" 值 from A
union all
select 名称,'3月' 月份,"3月" 值 from A
union all
select 名称,'4月' 月份,"4月" 值 from A)
where 名称='土豆'
结果:
with t(cate_displayname,info_waritername,count) as (
select '2014年','lizifeng',1 from dual
union all
select '历史沿革','wenqingwen',20 from dual
union all
select '领导讲话','lizifeng',3 from dual
)
SELECT cate_displayname,
nvl(lizifeng,0) as lizifeng,
nvl(wenqingwen,0) as wenqingwen
FROM t
PIVOT (
sum(count) ---- pivot_clause
FOR info_waritername ---- pivot_for_clause
IN ('lizifeng' as lizifeng,'wenqingwen' as wenqingwen) ---- pivot_in_clause
);
输出:
CATE_DISPLAYNAME LIZIFENG WENQINGWEN
------------------------ ---------- ----------
2014年 1 0
历史沿革 0 20
领导讲话 3 0
用union all
假设列名分别为 col1 cola colb...
select col1,cola
from tabname
where ...
union all
select col1,colb
from tabname
where ...
union all
select col1,colc
from tabname
where ...
union all
select col1,cold
from tabname
where ...
union all
select col1,cole
from tabname
where ...
union all
select col1,colf
from tabname
where ...
WITH A AS(SELECT ID_F,LINE_F,STAGE_F,UNITSTAGE_F,CAST(CHILDSTAGE_F AS VARCHAR(100)) AS CHILDSTAGE_F,PARENTID_F FROM 表名 WHERE PARENTID_F IS NULL
UNION ALL
SELECT 表名.ID_F,表名.LINE_F,表名.STAGE_F,表名.UNITSTAGE_F,CAST(A.CHILDSTAGE_F+表名.CHILDSTAGE_F AS VARCHAR(100)) AS CHILDSTAGE_F,表名.PARENTID_F
FROM 表名 JOIN A ON 表名.PARENTID_F=A.ID_F)
SELECT LINE_F,STAGE_F,UNITSTAGE_F,CHILDSTAGE_F
FROM A
WHERE PARENTID_F IS NOT NULL
姓名 数学 语文 姓名 张飞 赵云 庞统
张飞 60 61 数学 60 80 99
赵云 80 85 变成 语文 61 85 80
庞统 99 80
而且第一行为列名,不是表中的数据,这样的话
也就是第一个表下面三行的数据,变成第二个表下面两行的数据
这样还是可以的
oracle下可以用函数decode处理:
select 产品名称,
sum(decode(季度,'第一季度',销售额,0)) 第一季度销售额,
sum(decode(季度,'第二季度',销售额,0)) 第二季度销售额,
sum(decode(季度,'第三季度',销售额,0)) 第三季度销售额,
sum(decode(季度,'第四季度',销售额,0)) 第四季度销售额,
from 表名
group by 产品名称;