来自where子句中使用的select的聚合函数别名

时间:2013-10-03 09:14:01

标签: sql-server tsql

这里的错误在哪里:

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'。

3 个答案:

答案 0 :(得分:3)

您不能在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)

答案 1 :(得分:0)

您无法在WHERE子句中使用别名,因为SELECT语句在SELECT之前逻辑执行,因此它不会#39;看到名称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

答案 2 :(得分: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