关于AVG() group by , having, where 字句的使用

mlovex 2014-04-15 06:25:46
关于使用聚合Avg函数,Having / Where 字句的位置。

请问,为什么 1, 2 没问题; 3可以,4却不行呢?

1. select ID, AVG(Salary) from EMPLOYEE Group by ID Having ID in ('ID1', 'ID2') -- OK
2. select ID, AVG(Salary) from EMPLOYEE where ID in ('ID1', 'ID2') Group by ID -- OK

3. select ID, AVG(Salary) from EMPLOYEE Group by ID Having count(*)>=2 -- OK
4. select ID, AVG(Salary) from EMPLOYEE where count(*)>2 Group by ID -- Not OK
...全文
189 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
mlovex 2014-04-16
  • 打赏
  • 举报
回复
找到了,这个是正确解释 COUNT is an aggregate (or column) function rather than a scalar function. Aggregate functions operate over multiple rows. Scalar function operate on a single row. The WHERE clause tests a single row's values and the HAVING clause tests values aggregated or used as grouping values. Thus COUNT is allowed in the HAVING clause, but not in the WHERE clause.
benluobo 2014-04-15
  • 打赏
  • 举报
回复
如果需要在group中需要使用表中的原有字段,可以在group by 前面和后面都可以使用 如果需要在group中需要使用分组后的聚合函数,只能在having 中使用

5,889

社区成员

发帖
与我相关
我的任务
社区描述
IBM DB2 是美国IBM公司开发的一套关系型数据库管理系统,它主要的运行环境为UNIX(包括IBM自家的AIX)、Linux、IBM i(旧称OS/400)、z/OS,以及Windows服务器版本
社区管理员
  • DB2
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧