【问题标题】:Aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause聚合可能不会出现在 WHERE 子句中,除非它出现在 HAVING 子句中包含的子查询中
【发布时间】:2021-04-24 10:24:53
【问题描述】:

消息 147,第 15 级,状态 1,第 191 行
聚合可能不会出现在 WHERE 子句中,除非它位于 HAVING 子句或选择列表中包含的子查询中,并且被聚合的列是外部引用。

代码:

select  
    count(i.item_id), warehouse_id 
from 
    items_in_warehouse i
where 
    date_from >= '2021-01-01' 
    and date_from <= '2021-03-31' 
    and count(warehouse_id) >= 5 
    and count(warehouse_id) <= 10 
group by 
    warehouse_id;

我认为问题出在计数功能上。

【问题讨论】:

    标签: sql sql-server database tsql


    【解决方案1】:

    错误信息几乎是在告诉你如何修复它,你需要使用having 来过滤聚合:

    您可以在group by 之后使用having 进行过滤

    having count(warehouse_id) between 5 and 10;
    

    【讨论】:

      【解决方案2】:

      该消息表示聚合函数(count)只能用于在have子句中进行过滤

      select count(i.item_id), warehouse_id from items_in_warehouse i
      where date_from >= '2021-01-01' and date_from <= '2021-03-31'
      group by warehouse_id
      having count(warehouse_id) >= 5 and count(warehouse_id) <= 10; 
      

      除非它在有子句的子查询中

      select count(i.item_id), warehouse_id from items_in_warehouse i
      where date_from >= '2021-01-01' and date_from <= '2021-03-31'
      group by warehouse_id
      having (select count(1) from limits where limits.lower < count(i.item_id)) > 5
      

      类似的东西

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-08
        相关资源
        最近更新 更多