2017-07-21 233 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

它的工作。謝謝 –