日期:2014-05-17  浏览次数:20653 次

SQL语句执行效率慢,求各位高手帮忙
小弟是新手,为了做报表,写了一段SQL语句,结果速度很慢,大约要1分钟,帮忙看看如何才能优化。


语句如下:
select a.ccode,a.ccode_name,b.deptno,b.cDepName,b.大区,sum(b.JinE) JinE from
(select ccode ccode,ccode_name ccode_name from UFDATA_101_2012.dbo.code 
where ccode like '5100%' OR ccode like '5101%' OR ccode like '6601%' OR ccode like '6602%') a,
(select x.FeeAccCode,x.deptno,y.cDepName,case when y.cDepProp is null then '其它' else y.cDepProp end 大区,month(x.date) month,sum(x.JinE) JinE FROM 
(select T1.PlanNo,case when left(T1.DeptNoU8_Fee,4)='6601' then '6602' when left(T1.DeptNoU8_Fee,4)='6602' then '6601' else left(T1.DeptNoU8_Fee,4) end deptno,T3.shdate date,T2.FeeAccCode,T2.JE JinE 
from BSY_ACS_2012..c_YZK_SQ_Bill T1 left join BSY_ACS_2012..c_YZK_SQ_Bill_Detail T2 on T1.planid=T2.planid
inner join (select a.flowid,a.stepid,convert(varchar(12),a.updatetime,23) shdate from BSY_ACS_2012..c_workFlow_Step a where convert(varchar(20),a.updatetime,23)>='2012-10-01' and convert(varchar(20),a.updatetime,23)<='2012-10-31' and year(convert(varchar(20),a.updatetime,23))=2012 and a.stepid=(select max(stepid) from BSY_ACS_2012..c_workFlow_Step where flowid=a.flowid) and a.updatetime is not null) T3 on T1.FlowId=T3.FlowId
where T1.zjCode_FeeZC=T1.zjCode_FeeSR and T1.zjCode_FeeZC is not null and T1.zjCode_FeeSR is not null and T1.FlowStatus=2 and T1.FlowId is not null
and T1.JsTypeID<>106 and T1.DeptNoU8_Fee<>'' and T2.FeeAccCode is not null 
union all
select T1.PlanNo,case when left(T1.DeptNoU8_Fee,4)='6601' then '6602' when left(T1.DeptNoU8_Fee,4)='6602' then '6601' else left(T1.DeptNoU8_Fee,4) end deptno,T3.shdate date,T2.FeeAccCode,T2.JE JinE 
from BSY_ACS_2012..c_QKD_Bill T1 left join BSY_ACS_2012..c_QKD_Bill_Detail T2 on T1.planid=T2.planid
inner join (select a.flowid,a.stepid,convert(varchar(12),a.updatetime,23) shdate from BSY_ACS_2012..c_workFlow_Step a where convert(varchar(20),a.updatetime,23)>='2012-10-01' and convert(varchar(20),a.updatetime,23)<='2012-10-31' and year(convert(varchar(20),a.updatetime,23))=2012 and a.stepid=(select max(stepid) from BSY_ACS_2012..c_workFlow_Step where flowid=a.flowid) and a.updatetime is not null) T3 on T1.FlowId=T3.FlowId
where T1.zjCode_FeeZC=T1.zjCode_FeeSR and T1.zjCode_FeeZC is not null and T1.zjCode_FeeSR is not null and T1.FlowStatus=2 and T1.FlowId is not null
and T1.JsTypeID<>106 and T1.DeptNoU8_Fee<>'' and T2.FeeAccCode is not null 
) x LEFT JOIN UFDATA_101_2012.dbo.department y on x.deptno=y.cdepcode
group by x.deptno,y.cDepName,y.cDepProp,x.FeeAccCode,month(x.date)
) b
where b.FeeAccCode like a.ccode+'%'
group by a.ccode,a.ccode_name,b.deptno,b.cDepName,b.大区
order by a.ccode,a.ccode_name,b.deptno,b.cDepName

------解决方案--------------------
SQL code

创建一个索引
USE BSY_ACS_2012
go
create index idx_updatetime 
on c_workFlow_Step(updatetime)
include(flowid,stepid)
go