使用公用表表达式时“语法不正确”

时间:2016-10-16 16:16:02

标签: sql sql-server common-table-expression

WITH list_dedup (Company, duplicate_count) AS
(
     SELECT
         *,
         ROW_NUMBER() OVER (PARTITION BY Company ORDER BY Email) AS 'RowNumber'
     FROM
         Travels
)

错误

  

Msg 102,Level 15,State 1,Line 7
  ')'附近的语法不正确。

3 个答案:

答案 0 :(得分:3)

您缺少公用表表达式的最终选择( CTE定义之后):

WITH list_dedup  (Company,duplicate_count) As
(
  select *,
         ROW_NUMBER() OVER (PARTITION BY Company ORDER by Email) As "RowNumber"
  From Travels
)
select *  
from list_dedup;

但这不会因为CTE被定义为两个列(通过WITH list_dedup (Company,duplicate_count)),但您在CTE内的选择返回至少三列(公司,电子邮件,rownumber)。您需要调整CTE的列定义,或将其完全保留:

WITH list_dedup As
(
  select *,
         ROW_NUMBER() OVER (PARTITION BY Company ORDER by Email) As "RowNumber"
  From Travels
)
select *  
from list_dedup;

当定义列列表时,内部选择中的As "RowNumber"也没有意义,因为CTE定义定义了列名。在内部使用 CTE的任何别名都不会在其外部可见(如果with .. (...) as部分中指定了CTE列)。

答案 1 :(得分:3)

您只是设置您的CTE - 现在您需要使用它!

WITH list_dedup (Company, duplicate_count) AS
(
     SELECT
         *,
         ROW_NUMBER() OVER (PARTITION BY Company ORDER BY Email) AS 'RowNumber'
     FROM
         Travels
)
SELECT *
FROM list_dedup

答案 2 :(得分:0)

; WITH list_dedup(Company,duplicate_count)AS (      选择          *          ROW_NUMBER()OVER(公司按电子邮件分类)AS'RowNumber'      从          游记 )

SELECT * FROM list_dedup