【问题标题】:Subquery having clause error, what am I missing?子查询有子句错误,我错过了什么?
【发布时间】:2011-09-28 04:49:45
【问题描述】:

为什么会出现此错误?

 SELECT        unitCode
        FROM            Enrolment
        WHERE        count(studentID) >
         (SELECT        AVG(Students) AS avgstudents
        FROM            (SELECT        COUNT(*) AS Students
       FROM            Enrolment AS Enrolment_1
        GROUP BY unitCode) AS a))

【问题讨论】:

    标签: sql database sql-server-2005


    【解决方案1】:

    看起来最后有一个额外的括号。我不太了解 SQL,所以我不能说是否有任何问题(或者括号是否是一个问题)。

    【讨论】:

      【解决方案2】:

      在 where 子句中我们不能使用聚合函数。您可以在 HAVING 子句中使用 count(studentID) 函数。

      检查此示例,

      SELECT department, SUM(sales) as "Total sales"
      FROM order_details
      GROUP BY department
      HAVING SUM(sales) > 1000;
      

      【讨论】:

      • 我应该把有声明放在哪里?在子查询中?
      • 在 where cluse 的地方你只需要改变它,而不是在子查询中,SELECT count(), city FROM employee GROUP BY city HAVING count() = (SELECT max(count(*)) FROM employee GROUP BY city);
      • 能否请您更新您的代码,以便我可以正常查看? (我用手机浏览这个网站)
      • 只告诉你需要选择 unicode 或需要选择任何其他具有聚合函数的数据,如 sum()、count()。因为如果我们使用 having 子句,我们不能在没有任何聚合 func 值的情况下进行选择
      【解决方案3】:

      大卫检查一下,

      select count(*),unicode from Enrolement 
          having count(StudentID) > (select avg(Students) ad avgstudents,unitCode
          from table_Name where Enrolement = "some of ur condtion"
          group by unitCode) 
      

      需要更改格式化语法的查询.. 相应地检查您的查询业务。

      【讨论】:

      • 你能改变我在第一个问题中的确切代码来实现一个having子句吗?
      • 你能把我的 WHERE count(studentID) > 改成有声明,这样它就可以工作了吗?
      • 我只想显示值高于 avg(students) 子查询的 unitCodes
      【解决方案4】:

      试试这个:

      select unitCode
      from Enrolment
      group by unitCode
      having count(*) > (select avg(c.c) from (select count(*) as c from Enrolment group by unitCode) c);
      

      尊重:

      TSQL: Cannot perform an aggregate function AVG on COUNT(*) to find busiest hours of day

      【讨论】:

        猜你喜欢
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-14
        • 2019-08-29
        • 2015-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多