2017-07-21 3 views
0

i, einen Weg zu finden versuchen Abfrage zu optimieren, die ich glaube riesige time.This nehmen meine SQL-Abfrage:SQL-Aggregatfunktion Optimierung

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). 

Ich bin jede Spalte der Abfrage denke gleiche Logik ausführt außer Änderung am Tag als letzte Einschränkung. Gibt es eine Möglichkeit, die gesamte Logik zuerst zu berechnen, wie das Ergebnis in temporäre Tabelle zu leeren und dann mit Datum als where-Klausel abzufragen.

Antwort

0

Nutzungsbedingungs Aggregation:

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)); 

Anmerkung: I weggelassen die NULL Umwandlung auf der Annahme, dass zumindest eine Reihe entspricht die WHERE Bedingungen.

+0

hat es funktioniert. Vielen Dank –