2013-08-07 54 views

回答

2

你可以使用CROSS JOIN這樣的:爲cteFiveYear

SELECT 
    AVG(CASE WHEN instructorID = @instructorID THEN score END) InstructorSemesterAverage, 
    STDEVP(CASE WHEN instructorID = @instructorID THEN score END) InstructorSemesterSTDeviation, 
    AVG(CASE WHEN subjectCode = @subjectCode THEN score END) DepartmentSemesterAverage, 
    STDEVP(CASE WHEN subjectCode = @subjectCode THEN score END) DepartmentSemesterSTDeviation, 
    AVG(CASE WHEN [email protected] AND Q.year = @year AND semester = @semester THEN score END) ClassScore, 
    STDEVP(CASE WHEN [email protected] AND Q.year = @year AND semester = @semester THEN score END) ClassSTDeviation, 
    (SELECT DecTile FROM cteNtile WHERE instructorID = @instructorID)*10 DecTile, 
    X.DepartmentClassFiveYearAverage AS DepartmentClassFiveYearAverage, 
    X.DepartmentClassFiveYearSTDeviation AS DepartmentClassFiveYearSTDeviation, 
    X.InstructorClassFiveYearAverage AS InstructorClassFiveYearAverage, 
    X.InstructorClassFiveYearSTDeviation AS InstructorClassFiveYearSTDeviation 
FROM 
    cteMain Q CROSS JOIN cteFiveYear X 

這將防止多次執行(實際執行計劃見Number of Executions屬性)。

例如:如果您使用執行數據庫AdventureWorks2008R2此查詢

SELECT h.ProductID,h.StandardCost, 
     x.AvgPrice 
FROM Production.ProductCostHistory h 
CROSS JOIN (
    SELECT AVG(p.ListPrice) AvgPrice 
    FROM Production.Product p 
) x 

那麼實際執行計劃將 enter image description here

1

看一看下面

DECLARE @Table TABLE(
     ID INT, 
     Val VARCHAR(50), 
     TypeID INT 
) 

DECLARE @TableTypes TABLE(
     TypeID INT, 
     TypeName VARCHAR(50) 
) 

;WITh Vals AS (
     SELECT * 
     FROm @Table 
     WHERE ID > 10 
) 
, UsingVals1 AS (
     SELECT v.*, 
       tt.TypeName 
     FROm Vals v INNER JOIN 
       @TableTypes tt ON v.TypeID = tt.TypeID 
) 
, UsingVals2 AS (
     SELECT v.*, 
       tt.TypeName 
     FROm Vals v INNER JOIN 
       @TableTypes tt ON v.TypeID = tt.TypeID 
     WHERE tt.TypeName LIKE '%%' 
) 
SELECT * 
FROM UsingVals1 
UNION 
SELECT * 
FROM UsingVals2 

,接着在SQL Fiddle DEMO

你會從該丘壑CTE部分執行兩次執行計劃通知。

或許也看看How many times the T-SQL inside the CTE is executed?

+0

謝謝,我用Google搜索一下,但找不到任何確鑿,我想我因爲它像糖蜜一樣慢,所以必須使用臨時表。 – Preston

+2

@Preston,在開始使用臨時表之前,我建議查看執行計劃以確定查詢並確定索引策略是否會提高查詢性能 – zedfoxus

+0

@zfus不幸的是,這不是我的數據庫,它實際上是我大學的主要測試數據庫雖然他們不介意將我的查詢放在存儲過程中,但他們不會爲我做其他更改。 – Preston