0

有2个表称为

学生

  • 学生
  • camID FK

校园

  • camID PK
  • 凸轮名称

我正在尝试查找超过 4 名学生的校园,其中包括 camName、camID、(学生人数)

这是我到目前为止得到的

SELECT 
    students.camID, campus.camName, SUM(students.stuID) as [count] 
FROM 
    students 
JOIN 
    campus ON campus.camID = students.camID 
WHERE 
    [count] > 3 
GROUP BY 
    students.camID, campus.camName
ORDER BY 
    [count]

所有这一切都让我明白了一个错误,即“无效的 comlumn name 'count'。

4

3 回答 3

2

您不能在WHERE子句中使用列别名,因为在创建别名之前WHERE对子句进行评估。您也不能在子句中使用别名。HAVING

SELECT students.camID, campus.camName, COUNT(students.stuID) as studentCount
FROM students
JOIN campus
    ON campus.camID = students.camID
GROUP BY students.camID, campus.camName
HAVING COUNT(students.stuID) > 3
ORDER BY studentCount
于 2016-07-04T05:17:21.377 回答
0

第一个 SQL 产品不支持派生表,因此HAVING被发明出来。但是现在我们确实有派生表,所以我们不再需要HAVING它,而且确实会引起混淆(注意遗留功能永远不会从 SQL 标准中删除):

SELECT * 
  FROM (
        SELECT students.camID, campus.camName,
               SUM(students.stuID) as [count]
          FROM students 
               JOIN campus ON campus.camID = students.camID 
         GROUP 
            BY students.camID, campus.camName
       ) AS DT1
 WHERE [count] > 3
 ORDER
    BY [count]
于 2016-07-04T15:40:55.720 回答
0
    SELECT [t0].* FROM campus AS [t0]
    INNER JOIN (SELECT COUNT(*) AS [value], [t1].camID
    FROM students AS [t1]
    GROUP BY [t1].camID ) 
    AS [t2] ON [t0].camID = [t2].camID
    WHERE [t2].[value] > 3
于 2016-07-04T05:31:43.177 回答