赞
踩
前段时间,优化一张报表,在优化一条SQL查询时候,出现这样一个问题:
结果列中,有某一列因为条件关联原因,查询的结果会报:
ORA-01427: single-row subquery returns more than one row,顾名思义就是查询的结果出现多行了,与其他列保持不一致。
对于这种状况,之前开发的逻辑是这样的:先查询除了此列外的所有结果,然后再把此列的结果一一Reset到报表里。
这样无疑增加了很大的time cost,刚开始因为数据量不多,还没出现速度上的隐患,随时间推移,便暴露出来了。对此做法,以如今pro 数据增长速度坚决不可取。
后来在网上找了例子,可以把多行数据合并成一行显示,查询速度快得惊人。当时没有好好研究其原理,现在有空摸索下其实现逻辑。
Template SQL:
- SELECT
- PICKING_KEY,TRANSLATE (LTRIM (text, '/'), '*/', '*,') RESULT
- FROM (SELECT ROW_NUMBER () OVER (PARTITION BY PICKING_KEY ORDER BY PICKING_KEY,lvl DESC) rn,
- PICKING_KEY,
- text
- FROM (SELECT PICKING_KEY,
- LEVEL lvl,
- SYS_CONNECT_BY_PATH (ship_mark, '/') text
- FROM (SELECT
- ship_mark AS ship_mark,
- PICKING_KEY,
- ROW_NUMBER () OVER (PARTITION BY PICKING_KEY ORDER BY PICKING_KEY, ship_mark) x
- FROM
- ( SELECT
- DISTINCT ship_mark AS ship_mark,
- PICKING_KEY
- FROM con_pack_carton, con_pack_order
- WHERE CON_PACK_CARTON.CON_PACK_KEY = CON_PACK_ORDER.CON_PACK_KEY
- AND CON_PACK_ORDER.PICKING_KEY in ('0002927779')
- AND CON_PACK_ORDER.BATCH_NO = 1
- ORDER BY ship_mark,PICKING_KEY)
- ORDER BY ship_mark, PICKING_KEY)
- CONNECT BY PRIOR PICKING_KEY = PICKING_KEY AND PRIOR x - 1 = x)
- )
- WHERE rn = 1;
结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。