CTE中的子查询

时间:2013-10-23 11:21:51

标签: sql-server

我试图在学期结束后获得学生的身份 然后更新它的表中的状态 我可以在CTE中使用子查询吗?

;with temp As
(
    select CASE WHEN Status = 0 then 'Passed'
                when status >0 and status < 2 then 'uncomplete'
                else 'Failed' end Studentstatus
    from
    (
    SELECT     StudentID, 
               sum(CASE WHEN CourseStatus =1 then 1 else 0 end) Status
    FROM         StudentFinalResultsDetails
    group by StudentID
    )As t
)--the error in this line
问题是 ')'

附近的语法不正确

1 个答案:

答案 0 :(得分:2)

您不需要使用子查询,使用CTE或子查询;你混合它们,只需这样做:

with temp As
(
  SELECT   StudentID, 
           sum(CASE WHEN CourseStatus =1 then 1 else 0 end) Status
  FROM     StudentFinalResultsDetails
  group by StudentID
) -- You have to select something after the brackets 
select CASE WHEN Status = 0 then 'Passed'
                when status >0 and status < 2 then 'uncomplete'
                else 'Failed' end AS Studentstatus
from temp

或:删除WITH CTE

select CASE WHEN Status = 0 then 'Passed'
            when status >0 and status < 2 then 'uncomplete'
            else 'Failed' end Studentstatus
from
(
   SELECT     StudentID, 
           sum(CASE WHEN CourseStatus =1 then 1 else 0 end) Status
   FROM         StudentFinalResultsDetails
   group by StudentID
)As t

更新

问题中的查询问题,你必须移动部分:

 select CASE WHEN Status = 0 then 'Passed'
                when status >0 and status < 2 then 'uncomplete'
                else 'Failed' end AS Studentstatus`

WITH temp ( .... )括号的外部,然后选择你想要的任何内容。

由于:

  

CTE必须后跟一个SELECT,INSERT,UPDATE或DELETE   引用部分或全部CTE列的语句。 CTE也可以   在CREATE VIEW语句中指定,作为定义SELECT的一部分   意见陈述。

在您的查询中,您没有在其后面添加任何语句。见reference