Calling CTE multiple times in same query(在同一个查询中多次调用 CTE)
问题描述
我有一个相当复杂的查询,其中包含多个 CTE,但有 1 个主要 CTE,其他人都从中提取,这是否会导致该主要 CTE 被多次执行?
I have a fairly complicated query with multiple CTEs but 1 main CTE that the others all pull from, does this cause that main CTE to be executed multiple times?
推荐答案
你可以这样使用 CROSS JOIN:
You could use CROSS JOIN thus:
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
的多次执行(实际执行计划见 Number of Executions
属性).
This will prevent multiple executions (for actual execution plan see Number of Executions
property) for cteFiveYear
.
示例:如果您执行此查询
Example: If you execute this query
SELECT h.ProductID,h.StandardCost,
x.AvgPrice
FROM Production.ProductCostHistory h
CROSS JOIN (
SELECT AVG(p.ListPrice) AvgPrice
FROM Production.Product p
) x
使用 AdventureWorks2008R2
数据库,那么实际的执行计划将是
using AdventureWorks2008R2
database then the actual execution plan will be
这篇关于在同一个查询中多次调用 CTE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在同一个查询中多次调用 CTE
基础教程推荐
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01