【发布时间】:2018-08-12 23:38:33
【问题描述】:
我的存储过程执行得非常糟糕。关于如何改进它的任何建议?
select t2.ID,
t2.Transactions,
t2.StartTime,
t2.EndTime,
t2.Good,
t2.OK,
t2.Bad,
t1.PID,
t1.PName
from(
select distinct ID,
max([PID]) as MaxPID,
min([DATE_S]) as StartTime,
max([DATE_S]) as EndTime,
count([ID_P]) as Transactions,
coalesce(count(case when [STATUS] = 0 then 1 end), 0) as Good,
coalesce(count(case when [STATUS] = 1 then 1 end), 0) as Warning,
coalesce(count(case when [STATUS] > 1 then 1 end), 0) as Bad
from [dbo].[Table1]
where CONVERT(date, [DATE_S]) between CONVERT(date, @StartDate) and
CONVERT(date, @EndDate)
group by ID) t2
LEFT join [dbo].[Table2] t1 on t2.MaxPID = t1.[PID]
order by ID desc
非常感谢任何提示。
【问题讨论】:
-
DISTINCT超过GROUPed 已经没有多大意义。另外,我怀疑COUNT()是否按照您认为的方式工作。为此,您可能希望使用SUM()。 (因为无论如何我都在使用它,所以使用t1作为Table2的别名有点令人困惑(反之亦然))
标签: sql-server optimization query-optimization