gpt4 book ai didi

sql - 在同一查询中多次调用 CTE

转载 作者:行者123 更新时间:2023-12-02 16:43:13 28 4
gpt4 key购买 nike

我有一个相当复杂的查询,其中包含多个 CTE,但有 1 个主 CTE,其他所有 CTE 都从中提取,这是否会导致该主 CTE 被执行多次?

最佳答案

您可以这样使用 CROSS JOIN:

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 bannerCRN=@CRN AND Q.year = @year AND semester = @semester THEN score END) ClassScore,
STDEVP(CASE WHEN bannerCRN=@CRN 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

这将防止 cteFiveYear 的多次执行(有关实际执行计划,请参阅执行次数属性)。

示例:如果执行此查询

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

使用AdventureWorks2008R2数据库,那么实际的执行计划将是 enter image description here

关于sql - 在同一查询中多次调用 CTE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18094760/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com