以下查询在没有ttfj_wtd和ttfj_mtd子查询的情况下运行得非常快。但如果没有重新加入,他们会跑5分多钟。关于如何调整它的任何想法?
select eid, tech_id, tech_name, w_start, w_end, m_start, m_end
,(select firstname+' '+lastname from ems_nyc_employee where eid=a.supeid) as SupName
,(select firstname+' '+lastname from ems_nyc_employee where eid=a.mngreid) as MngrName
,activitydate
,shift_start+' - '+shift_end as [shift]
,shift_start_time
,login_time
,first_ip_time
,datediff(mi, shift_start_time, first_ip_time) as ttfj_yest
,(select avg(datediff(mi, shift_start_time, first_ip_time)) from arr_tech a2 where a2.eid=a.eid and a2.activitydate between w_start and w_end) as ttfj_wtd
,(select avg(datediff(mi, shift_start_time, first_ip_time)) from arr_tech a2 where a2.eid=a.eid and a2.activitydate between m_start and m_end) as ttfj_mtd
from
arr_tech a, dates d
where d.rep_date=convert(date, getdate()-1) and a.activitydate=convert(date, getdate()-1)
答案 0 :(得分:0)
这是为了便于阅读而修改的代码:
select eid, tech_id, tech_name, w_start, w_end, m_start, m_end,
(select firstname+' '+lastname
from ems_nyc_employee e
where e.eid = a.supeid
) as SupName,
(select firstname+' '+lastname
from ems_nyc_employee e
where e.eid = a.mngreid
) as MngrName,
activitydate,
(shift_start+' - '+shift_end) as [shift],
shift_start_time,
login_time,
first_ip_time,
datediff(mi, shift_start_time, first_ip_time) as ttfj_yest,
(select avg(datediff(mi, shift_start_time, first_ip_time))
from arr_tech a2
where a2.eid = a.eid and a2.activitydate between w_start and w_end
) as ttfj_wtd,
(select avg(datediff(mi, shift_start_time, first_ip_time))
from arr_tech a2
where a2.eid = a.eid and a2.activitydate between m_start and m_end
) as ttfj_mtd
from arr_tech a join
dates d
on a.activitydate = d.rep_date
where a.activitydate = convert(date, getdate() - 1);
首先,您需要外部查询的索引:arr_tech(rep_date)
和dates(rep_date)
。
然后,您需要子查询的索引:ems_nyc_employee(eid, firstname, lastname)
和arr_tech(eid, m_start, m_end)
。
如果这些索引不起作用,您可能需要重写查询。但是,这可能就足够了。
关于格式化的说明:
FROM
子句中使用逗号; 始终使用显式JOIN
语法。