`
hz_chenwenbiao
  • 浏览: 991882 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

SQL Group by 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"的表:

 

Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100

 

And This SQL:
这是条SQL:

 

SELECT Company, SUM(Amount) FROM Sales

 

Returns this result:
返回的结果为:

 

Company SUM(Amount)
W3Schools 17100
IBM 17100
W3Schools 17100

 

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:
返回的结果为:

 

Company SUM(Amount)
W3Schools 12600
IBM 4500

 


 

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"的表:

 

Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100

 

This SQL:
SQL语句:

 

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

 

Returns this result
返回的结果为

 

Company SUM(Amount)
W3Schools 12600

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics