2017-07-21 198 views
0

我试图找到一种方法来优化查询我相信这是冒着巨大time.This是我的sql查询:SQL聚合函数优化

select 
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountID and ClientID = @clientidvalue and status=2 and (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @sunday), 0), 
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountID and ClientID = @clientidvalue and status=2 and (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @monday), 0), 
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountID and ClientID = @clientidvalue and status=2 and (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @tuesday), 0), 
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountID and ClientID = @clientidvalue and status=2 and (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @wednesday), 0), 
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountID and ClientID = @clientidvalue and status=2 and (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @thursday), 0), 
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountID and ClientID = @clientidvalue and status=2 and (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @friday), 0), 
ISNULL((select sum(s.durationp) from Schedule s where AccountID = @AccountsqlID and ClientID = @clientidvalue and status=2 and (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)) and s.Date= @saturday), 0). 

我想查询的每一列执行相同的逻辑除了作为最后限制的一天中的变化。有没有什么办法可以先计算出整个逻辑,比如将结果刷新到临时表中,然后用date作为where子句查询它。

回答

0

使用条件汇总:

select sum(case when s.Date = @sunday then s.durationp else 0 end) as sunday, 
     sum(case when s.Date = @monday then s.durationp else 0 end) as monday, 
     . . . 
from Schedule s 
where AccountID = @AccountID and ClientID = @clientidvalue and 
     status = 2 and 
     (@StaffID = 0 OR (@StaffID <> 0 AND s.StaffID = @StaffID)); 

注:我离开了上至少有一个排的WHERE条件相匹配的假设NULL转换。

+0

它的工作。谢谢 –