我想将公用表表达式的结果集与现有表连接起来。使用以下查询中给出的group by子句会出现问题。有谁能告诉我如何加入这两张桌子?。
With CTEQuery
as
(SELECT StudentOnlineExamCourseAnswer.StudentID, StudentOnlineExamCourseAnswer.OnlineExamID, StudentOnlineExamCourseAnswer.CourseID,
StudentOnlineExamCourseAnswer.CentreID,
case QuestionBank.ComplexLevelID when 1 then (2) when 2 then (4) when 3 then (6) when 4 then (8) when 5 then (10) end as Mark
FROM QuestionBank INNER JOIN
StudentOnlineExamCourseAnswer ON QuestionBank.Answer = StudentOnlineExamCourseAnswer.Answer AND
QuestionBank.QuestionID = StudentOnlineExamCourseAnswer.QuestionID)
select StudentID, OnlineExamID ,CourseID , CentreID , sum(Mark) as 'Total Marks' from CTEQuery
group by StudentID, OnlineExamID ,CourseID , CentreID
答案 0 :(得分:1)
您可以为单个选择定义多个CTE,每个CTE可以引用先前定义的CTE。所以你可以这样做:
With CTEQuery
as
(SELECT StudentOnlineExamCourseAnswer.StudentID, StudentOnlineExamCourseAnswer.OnlineExamID, StudentOnlineExamCourseAnswer.CourseID,
StudentOnlineExamCourseAnswer.CentreID,
case QuestionBank.ComplexLevelID when 1 then (2) when 2 then (4) when 3 then (6) when 4 then (8) when 5 then (10) end as Mark
FROM QuestionBank INNER JOIN
StudentOnlineExamCourseAnswer ON QuestionBank.Answer = StudentOnlineExamCourseAnswer.Answer AND
QuestionBank.QuestionID = StudentOnlineExamCourseAnswer.QuestionID)
, SummarizedCTE as (
select StudentID, OnlineExamID ,CourseID , CentreID , sum(Mark) as TotalMark from CTEQuery
group by StudentID, OnlineExamID ,CourseID , CentreID)
select <new query involving joining SummarizedCTE with the "other table" referenced in your discussion>
答案 1 :(得分:0)
例如
with demoCTE
as
(
select id from table1
) select * from demoCTE
join table2
on demoCTE.id= table2.id
答案 2 :(得分:0)
您需要先创建CTE,然后在下一个SELECT
语句中使用它。
WITH cteTest (Column1) AS
(
SELECT column1
FROM table1
)
SELECT *
FROM cteTest
JOIN Table2
ON cteTest.column1 = Table2.column1