oracle 列名不确定 行转列

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了oracle 列名不确定 行转列相关的知识,希望对你有一定的参考价值。

table1 字段id1, cgr; table2字段id2,id1,gg ,table3字段id3,id2,单位名称,单价,总价
table1 与table2是一对多,tabl2与table3一对多,显示时要根据table3中记录数添加列,列明是table3中的单位名称。

select decode(t.rn,1,t.单位名称) as 单位名称1 ,
decode(t.rn,2,t.单位名称) as 单位名称2,
decode(t.rn,3,t.单位名称) as 单位名称3,
from (
select c.单位名称,to_number() over(partition by c.单位名称) as rn
from table1 a,table2 b,table3 c
where a.id1 = b.id1
and b.id2=c.id2
) t ;
这是在知道多少行记录数的情况下这样实现,如果不知道多少行,则最好用个中间表,搞个语句块,把相关的数先放到中间表在进行处理。
参考技术A select
Student,
max(case Course when'数学'then Score else0end) as 数学,
max(case Course when'物理'then Score else0end) as 物理,
max(case Course when'英语'then Score else0end) as 英语,
max(case Course when'语文'then Score else0end) as 语文
from
Class
groupby Student;

你试试?

oracle行转列实践

在Oracle 11g中,Oracle 增加了2个查询:pivot(行转列) 和unpivot(列转行)

pivot(聚合函数 for 列名 in(类型)) ,其中 in(‘‘) 中可以指定别名,in中还可以指定子查询

行转列:

select * from rhsa_gcfx_result order by org_id,item,dictname

技术分享

 select org_id,item,sum(value) from rhsa_gcfx_result where dictname = ‘入院途径‘ and 1=1 group by item,org_id order by org_id,item

技术分享

将item列转换成行

select * from (select org_id,item,sum(value) value from rhsa_gcfx_result where dictname = ‘入院途径‘ and 1=1 group by item,org_id)
pivot (sum(value) for item in (‘1. 急诊‘ 急诊 , ‘2. 门诊‘ 门诊, ‘3. 其他医疗机构转入‘ 其他医疗机构转入, ‘9. 其他‘ 其他))

技术分享

 


以上是关于oracle 列名不确定 行转列的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server 动态行转列(参数化表名分组列行转列字段字段值)

SQL Server 动态行转列(参数化表名分组列行转列字段字段值)

SQL2000行转列于列转行问题,急~~~ (部门是不确定几个的)

oracle 11g 行转列后的列名怎么在外层SQL中使用

【求助】有关oracle 动态行转列

oracle行转列实践