`
yesjavame
  • 浏览: 656343 次
  • 性别: Icon_minigender_2
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

Oracle合并多行为多列

阅读更多

oracle 如何聚合多行函数

在BEA论坛上看一位"专家"写的大作,一条SQL语句是

select	r.xm, 

	substr(r.csrq,1,4)||'年'||substr(r.csrq,5,2)||'月'||substr(r.csrq,7,2)||'日' csrq,

	(select dictvalue from zh_dictvalue where dictcode=xb and dictname='rk_xb') xb,

	(select dictvalue from zh_dictvalue where dictcode=mz and dictname='rk_mz') mz,

	(select dictvalue from zh_dictvalue where dictcode=ssxq and dictname='rk_xzqh') ssxq,

	xz,

	xp,

	xz,

	fwcs 



from czrk_jbxx r,rk_zpxx p 



where r.gmsfhm=p.gmsfhm  and rownum<2

朋友看了一会,然后问我 (select dictvalue from zh_dictvalue where dictcode=xb and dictname='rk_xb') xb, (select dictvalue from zh_dictvalue where dictcode=mz and dictname='rk_mz') mz, (select dictvalue from zh_dictvalue where dictcode=ssxq and dictname='rk_xzqh') ssxq, 这里如何优化,也就是符合条件的三条记录要合并成一条记录.

其实之前有好多这样的问题,但没有一个好的方案,都是嵌套太多,性能损失很大,把三条记录的结果合并.如果最后的sql语句中的select超过三次,那真的还不如直接这样查询.

不过首先这个方法是错误的,因为这三次都在原表中查询,性能损失很大,其实如果是5条,10条,20条,100条.这样的语句写起来就累死人了.

之前有人提供了几个方案,但都是连成字符串还不是形成多列.真正形成多列应该是用分析函数:

这样实际上只能原表做一次查询,然后得到的结果集在显示的时候被提前到一行上形成多列.

select * from (

       select name,

              lead(name,1) over (order by name) as name1, 

              lead(name,2) over (order by name) as name2, 

              lead(name,3) over (order by name) as name3, 

              lead(name,4) over (order by name) as name4

              from tb_customer where 条件

) t

where t.name4 is not null

这样原来的行数越多节省的性能越高,因为实际原表查询只有一次,后来只是对内存中的结果做合并.上面的那个例子就是

select * from (	

	select	dictvalue as mz,

		lead(dictvalue,1) over (order by dictcode) as ssxq, 

		lead(dictvalue,2) over (order by dictcode) as xb, 

	from zh_dictvalue 

	where (dictcode=xb and dictname='rk_xb') 

		or (dictcode=mz and dictname='rk_mz')

		or (dictcode=ssxq and dictname='rk_xzqh')

) t

where t.ssxq not null
注意在order by dictcode后,苛as后面的名称被调整了.否则dictvalue和命名的列就不对应了.
分享到:
评论
1 楼 Tank03 2013-04-11  
select
  sum(decode(FEE_NAME, '租金(含中介及开票税金)', FEE_MONEY, 0)),
  sum(decode(FEE_NAME, '固定电话', FEE_MONEY, 0))
  from t_os_costing t
where t.group_id = '145' and t.costing_month = '2013-04'



这样不行么?

相关推荐

Global site tag (gtag.js) - Google Analytics