谁能帮我优化一下?最好写明为什么会运行速度如此慢?
select stmstno,stname,stextend2,ststudytype,语文
,(select count(*)+1 from dmstm
where stmsubject='语文'
and stmtype='测验2'
and stmyear='20062007'
and stmpd='第一学期'
and substring(stmstno,2,4)=substring(Score.stmstno,2,4)
and stmsm>Score.语文) as 语文班级
,(select count(*)+1 from dmstm
where stmsubject='语文'
and stmtype='测验2'
and stmyear='20062007'
and stmpd='第一学期'
and substring(stmstno,2,2)='06'
and stmsm>Score.语文) as 语文年级
,数学
,(select count(*)+1 from dmstm
where stmsubject='数学'
and stmtype='测验2'
and stmyear='20062007'
and stmpd='第一学期'
and substring(stmstno,2,4)=substring(Score.stmstno,2,4)
and stmsm>Score.数学) as 数学班级
,(select count(*)+1 from dmstm
where stmsubject='数学'
and stmtype='测验2'
and stmyear='20062007'
and stmpd='第一学期'
and substring(stmstno,2,2)='06'
and stmsm>Score.数学) as 数学年级
,英语
,(select count(*)+1 from dmstm
where stmsubject='英语'
and stmtype='测验2'
and stmyear='20062007'
and stmpd='第一学期'
and substring(stmstno,2,4)=substring(Score.stmstno,2,4)
and stmsm>Score.英语) as 英语班级
,(select count(*)+1 from dmstm
where stmsubject='英语'
and stmtype='测验2'
and stmyear='20062007'
and stmpd='第一学期'
and substring(stmstno,2,2)='06'
and stmsm>Score.英语) as 英语年级
,物理
,(select count(*)+1 from dmstm
where stmsubject='物理'
and stmtype='测验2'
and stmyear='20062007'
and stmpd='第一学期'
and substring(stmstno,2,4)=substring(Score.stmstno,2,4)
and stmsm>Score.物理) as 物理班级
,(select count(*)+1 from dmstm
where stmsubject='物理'
and stmtype='测验2'
and stmyear='20062007'
and stmpd='第一学期'
and substring(stmstno,2,2)='06'
and stmsm>Score.物理) as 物理年级
,化学
,(select count(*)+1 from dmstm
where stmsubject='化学'
and stmtype='测验2'
and stmyear='20062007'
and stmpd='第一学期'
and substring(stmstno,2,4)=substring(Score.stmstno,2,4)
and stmsm>Score.化学) as 化学班级
,(select count(*)+1 from dmstm
where stmsubject='化学'
and stmtype='测验2'
and stmyear='20062007'
and stmpd='第一学期'
and substring(stmstno,2,2)='06'
and stmsm>Score.化学) as 化学年级
,三门总分
,八门总分 into temptable
from
(select *
,(语文+数学+英语) as 三门总分
,(语文+数学+英语+物理+化学) as 八门总分
from(
select stmstno
,stextend2
,stname
,isnull(ststudytype,0) as ststudytype
,max (case stmsubject when '语文' then stmsm else '' end) as 语文
,max (case stmsubject when '数学' then stmsm else '' end) as 数学
,max (case stmsubject when '英语' then stmsm else '' end) as 英语
,max (case stmsubject when '物理' then stmsm else '' end) as 物理
,max (case stmsubject when '化学' then stmsm else '' end) as 化学
from dmstm,dmst
where stmtype='测验2'
and stmyear='20062007'
and stmpd='第一学期'
and substring(stmstno,2,2)='06'
and stmstno=stno
group by stmstno,stname,ststudytype,stextend2)aa)Score
select
(select count(*)+1 from temptable
where 三门总分>b.三门总分) as 三门名次
,(select count(*)+1 from temptable
where 八门总分>b.八门总分) as 八门名次
,case ststudytype when '0' then '' else '*' end as studytype
,* into temptable1
from temptable b
select * from temptable1
order by stmstno