表结构及数据内容
code name num
01 test1
0101 test2 10
0102 test3 10
02 test4
0201 test5
020101 test6 20
020102 test7 20
0202 test8 10希望通过一个条sql语句(或者优化的方法),导出汇总报表,如下
code name num
01 test1 20
0101 test2 10
0102 test3 10
02 test4 50
0201 test5 40
020101 test6 20
020102 test7 20
0202 test8 10目前采用的语句是
select a.code ,
a.name
(select sum(num) from T b where b.code like a.code+'%') as sum_num
from T a
order by a.code这个语句的运行效率是非常低的,上万条数据,耗费2~3分钟的运行时间请大家分析一下,最优化的方式写出sql,不限制sql语句的条数(这些语句是放在存储过程中执行的)。
code name num
01 test1
0101 test2 10
0102 test3 10
02 test4
0201 test5
020101 test6 20
020102 test7 20
0202 test8 10希望通过一个条sql语句(或者优化的方法),导出汇总报表,如下
code name num
01 test1 20
0101 test2 10
0102 test3 10
02 test4 50
0201 test5 40
020101 test6 20
020102 test7 20
0202 test8 10目前采用的语句是
select a.code ,
a.name
(select sum(num) from T b where b.code like a.code+'%') as sum_num
from T a
order by a.code这个语句的运行效率是非常低的,上万条数据,耗费2~3分钟的运行时间请大家分析一下,最优化的方式写出sql,不限制sql语句的条数(这些语句是放在存储过程中执行的)。
a.code,
a.name,
sum(b.num) as num
from
T a,
T b
where
b.code like a.code+'%'
group by
a.code,a.name
我做了测试,速度更慢了,上面我给出的a表在项目中实际上是一个视图!
采用您给出的方法,对两个视图进行查询,6000多行的数据,15分钟都没有出来啊。
如果我去除
where b.code like a.code+'%'
这个语句,则3秒就可以显示看来瓶颈还是在这里啊,继续请教!!!
--------------------------------------
关键不在视图的优化问题上,而且我的视图有外关联(不能创建索引)
我做过测试,视图这个快执行很快一秒左右,主要是“where b.code like a.code+'%'“这个
条件,非常的慢,我看了一下,和
select a.code ,
a.name
(select sum(num) from T b where b.code like a.code+'%') as sum_num
from T a
order by a.code
的效率是一样的!
真的好痛苦啊!!!
高手们,再想想办法吧!!!这样的问题,我想做系统的人都应该遇到吧
code name num upcode
01 test1
0101 test2 10 01
0102 test3 10 01
02 test4
0201 test5 02
020101 test6 20 02
020102 test7 20 02
0202 test8 10 02那么要得出你的查询结果的话 就可以这么写
select a.code ,
a.name
(select sum(num) from T b where b.code=a.upcode) as sum_num
from T a
order by a.code