无法使用join创建公用表表达式

时间:2017-11-02 18:41:43

标签: sql-server tsql

出于某种原因,我无法通过查询进行CTE:

SELECT LetterGrade, ES.Classification 
FROM Enrollment AS EN 
JOIN Students AS ES ON EN.StudentID = ES.StudentID

本声明:

WITH [DERIVED] AS
(
    SELECT LetterGrade, ES.Classification 
    FROM Enrollment AS EN 
    JOIN Students AS ES ON EN.StudentID = ES.StudentID
)

引发错误:

  

Msg 102,Level 15,State 1,Line 5
  ')'

附近的语法不正确

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

有两种方法。

选项1:使用内部查询:

select ...
from (SELECT LetterGrade, ES.Classification
      FROM Enrollment AS EN
      JOIN Students AS ES ON EN.StudentID = ES.StudentI) as Derived
where ...

此语法非常便于携带。它适用于所有主要的SQL数据库。

选项2:使用较少支持的CTE语法:

with Derived as (
    SELECT LetterGrade, ES.Classification
    FROM Enrollment AS EN
    JOIN Students AS ES ON EN.StudentID = ES.StudentI)
select ...
from Derived
where ...

这样便携性较差(例如postgres支持它,mysql不支持) 它也可以更容易阅读,如果多次提到CTE可以提供编码和性能优势。