【问题标题】:Trying to use a count column in the where part of a query尝试在查询的 where 部分中使用计数列
【发布时间】:2016-07-04 05:13:51
【问题描述】:

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

【问题讨论】:

    标签: sql sql-server ssms-2014


    【解决方案1】:

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

    【讨论】:

    • 不应该在have子句中,而不是where子句中吗?
    • @ZLK 有助于阅读问题。让我们看看这是否会被否决。
    • 我的意思是它应该是 GROUP BY students.camID, campus.camName HAVING SUM(students.stuID) > 3,而不是 where 子句中的聚合。
    • 是的!第二个有效,但我必须使用SUM(students.stuID) 来防止无效的列名。非常感谢
    • @onedaywhen 我不知道这个问题的答案,而答案是特定于 RDMBS 的。我自己很好奇,所以我最近asked this very question.
    【解决方案2】:
        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
    

    【讨论】:

      【解决方案3】:

      第一个 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]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-12
        • 1970-01-01
        • 1970-01-01
        • 2020-10-08
        • 2020-11-18
        • 1970-01-01
        相关资源
        最近更新 更多