各位大神,这个怎么优化好,我这个好慢,执行需要20多秒
ALTER       procedure [dbo].[spWorkAttendanceByOrg]
@OrgCode varchar(10),
@Day datetime
asset nocount on
declare @t1 table(日期 smalldatetime,时间 varchar(10),工号 varchar(10),id int identity(1,1))
insert into @t1select FDate,FTime,staffno from (
select distinct convert(varchar(10),FDate,120) as FDate,FTime,staffno from workTime a
where exists(select 1 from employees e left join employeedimission ed on e.employeeid=ed.employeeid where staffno=a.staffno and (e.dimission=0 or datediff(month,@Day,dimissiondate)>=0) and orgcode like @OrgCode+'%')and FDate>=@Day and FDate<dateadd(day,1,@Day)  and isnull(aflag,0)=0) a
order by staffno,ftime
declare @t2 table(日期 smalldatetime,时间 varchar(10),工号 varchar(10),num int)
insert into @t2 
SELECT 日期,时间,工号,Num=(SELECT COUNT(1) FROM @t1 WHERE 日期=a.日期 AND id<=a.id and 工号=a.工号) FROM @t1 aselect 
工号,e.employeename as 姓名,日期,
[刷卡1]=min(case num when 1 then 时间 end),
[刷卡2]=min(case num when 2 then 时间 end),
[刷卡3]=min(case num when 3 then 时间 end),
[刷卡4]=min(case num when 4 then 时间 end),
[刷卡5]=min(case num when 5 then 时间 end),
[刷卡6]=min(case num when 6 then 时间 end),
[刷卡7]=min(case num when 7 then 时间 end),
[刷卡8]=min(case num when 8 then 时间 end),
[刷卡9]=min(case num when 9 then 时间 end),
[刷卡10]=min(case num when 10 then 时间 end)
from @t2 a
left join employees e on a.工号=e.staffno
group by 工号,日期,e.employeenameset nocount off