sql 之having

在select 语句中可以使用group by 子句将行划分成较小的组,然后,使用聚组函数返回每一个组的汇总信息,另外,可以使用having子句限制返回的结果集。group by 子句可以将查询结果分组,并返回行的汇总信息Oracle 按照group by 子句中指定的表达式的值分组查询结果。

   在带有group by 子句的查询语句中,在select 列表中指定的列要么是group by 子句中指定的列,要么包含聚组函数

   select max(sal),job emp group by job;

   (注意max(sal), job 的job并非一定要出现,但有意义 )

   查询语句的select 和group by ,having 子句是聚组函数唯一出现的地方,在where 子句中不能使用聚组函数。

  select deptno,sum(sal) from emp where sal>1200 group by deptno having sum(sal)>8500 order by deptno;

  当在gropu by 子句中使用having 子句时,查询结果中只返回满足having条件的组。在一个sql语句中可以有where子句和having子句。having 与where 子句类似,均用于设置限定条件

 

  where 子句的作用是在对查询结果进行分组前,将不符合where条件的行去掉,即在分组之前过滤数据,条件中不能包含聚组函数,使用where条件显示特定的行。

  having 子句的作用是筛选满足条件的组,即在分组之后过滤数据,条件中经常包含聚组函数,使用having 条件显示特定的组,也可以使用多个分组标准进行分组。

  查询每个部门的每种职位的雇员数

  select deptno,job,count(*) from emp group by deptno,job;

GROUP BY...

GROUP BY... was added to SQL because aggregate functions (like SUM) return the aggregate of all column values every time they are called, and without the GROUP BY function it was impossible to find the sum for each individual group of column values.

GROUP BY...之所以加到SQL中去是因为集合函数(像SUM)每当他们被访问时就会返回集合所有栏目的值,而且没有GROUP BY的话就不能够找出单独一种栏目所累计的值了。

The syntax for the GROUP BY function is:

使用GROUP BY函数的语法为:

 

SELECT column,SUM(column) FROM table GROUP BY column


 

 

GROUP BY Example

举例

This "Sales" Table:

这是张名为"Sales"的表:

CompanyAmount
W3Schools5500
IBM4500
W3Schools7100

And This SQL:

这是条SQL:

 

SELECT Company, SUM(Amount) FROM Sales

Returns this result:

返回的结果为:

CompanySUM(Amount)
W3Schools17100
IBM17100
W3Schools17100

The above code is invalid because the column returned is not part of an aggregate. A GROUP BY clause will solve this problem:

上面这些代码几乎是无效的,因为栏目所返回的数值并不属于我们想要的那种合计。使用 GROUP BY子句可以解决这个问题:

 

SELECT Company,SUM(Amount) FROM Sales GROUP BY Company

Returns this result:

返回的结果为:

CompanySUM(Amount)
W3Schools12600
IBM4500

 

 

HAVING...

HAVING... was added to SQL because the WHERE keyword could not be used against aggregate functions (like SUM), and without HAVING... it would be impossible to test for result conditions.

WHERE关键字在使用集合函数时不能使用,所以在集合函数中加上了HAVING来起到测试查询结果是否符合条件的作用。

The syntax for the HAVING function is:

HAVING的使用语法为:

 

SELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column) condition value

This "Sales" Table:

这是名为"Sales"的表:

CompanyAmount
W3Schools5500
IBM4500
W3Schools7100

This SQL:

SQL语句:

 

SELECT Company,SUM(Amount) FROM Sales GROUP BY Company HAVING SUM(Amount)>10000

Returns this result

返回的结果为

CompanySUM(Amount)
W3Schools12600
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值