2

这里的错误在哪里:

SELECT Users.UserID, 
   ClassCourses.CourseID,
   ClassCourses.MinMark,
   sum(StudentMark) as SMark    
FROM   Users 
INNER JOIN UserExams ON Users.UserID = UserExams.UserID
INNER JOIN Exams ON UserExams.ExamID = Exams.ExamID 
INNER JOIN ClassCourses ON Exams.ClassID = ClassCourses.ClassID AND Exams.CourseID = ClassCourses.CourseID
where  ClassCourses.MinMark> SMark
group by Users.UserID, ClassCourses.CourseID,ClassCourses.MinMark

我收到一个错误:

列名“SMark”无效。

4

3 回答 3

4

您不能在 WHERE 子句中使用列别名。此外,在比较聚合结果时,必须在应用 GROUP BY 之后使用 HAVING 子句。

做这样的事情:

SELECT Users.UserID, 
    ClassCourses.CourseID,
    ClassCourses.MinMark,
    sum(StudentMark) as SMark    
FROM   Users 
INNER JOIN UserExams ON Users.UserID = UserExams.UserID
INNER JOIN Exams ON UserExams.ExamID = Exams.ExamID 
INNER JOIN ClassCourses ON Exams.ClassID = ClassCourses.ClassID AND Exams.CourseID = ClassCourses.CourseID
GROUP BY Users.UserID, ClassCourses.CourseID,ClassCourses.MinMark
HAVING ClassCourses.MinMark > sum(StudentMark)
于 2013-10-03T09:18:14.400 回答
0

您不能在WHERE子句中使用别名,因为该WHERE语句在逻辑上在 之前执行SELECT,因此它看不到该名称SMark

您可以将其放在子查询中,并像这样在外部查询中进行过滤:

SELECT *
FROM
(
    SELECT 
      Users.UserID, 
      ClassCourses.CourseID,
      ClassCourses.MinMark,
      sum(StudentMark) as SMark    
    FROM   Users 
    INNER JOIN UserExams     ON Users.UserID     = UserExams.UserID
    INNER JOIN Exams         ON UserExams.ExamID = Exams.ExamID 
    INNER JOIN ClassCourses  ON Exams.ClassID    = ClassCourses.ClassID
                            AND Exams.CourseID   = ClassCourses.CourseID
    group by Users.UserID, 
             ClassCourses.CourseID,
             ClassCourses.MinMark
) AS t
where  MinMark> SMark
于 2013-10-03T09:17:57.497 回答
0

试试这个:

select 
    * 
from 
    (

    SELECT Users.UserID, 
       ClassCourses.CourseID,
       ClassCourses.MinMark,
       sum(StudentMark) as SMark    
    FROM   Users 
    INNER JOIN UserExams ON Users.UserID = UserExams.UserID
    INNER JOIN Exams ON UserExams.ExamID = Exams.ExamID 
    INNER JOIN ClassCourses ON Exams.ClassID = ClassCourses.ClassID AND Exams.CourseID = ClassCourses.CourseID

    group by Users.UserID, ClassCourses.CourseID,ClassCourses.MinMark
    )a
where  MinMark > SMark
于 2013-10-09T10:33:37.377 回答