SQL-select下的四个重要子句用法 (转载)

来源:互联网 发布:ce5..4源码 编辑:程序博客网 时间:2024/05/09 07:53
group  by子句
group   by   [ all ]  group_by_expression  [ ,n ]
[ with {cube|rollup} ]
cube:列的各种组合按组统计行
rollup:第一个分组条件指这一列统计行
例:
select  name sex 
    
from  taihang
    
group   by  name sex
    
with  cube
   
/ with  rollup

having子句
和group BY子句通常一起使用,作用于组
having   < search_condition >
count ( * ):符合条件记录行数
例:查询有多个员工工资不低于1000的部门ID号
select  id, count ( * )
from  taihang
where  wage >= 1000
group   by  id
having   count ( * ) > 1

order  by子句
排序方式
order   by {order_by_expression  [ asc|desc ] } [ ,n ]
asc升序,默认
desc降序
例:第一个字段升序,第二个字段降序
select  字段1, 字段2
from  taihang
order   by  字段1  desc ,字段2
例:查询年龄最大的三个人
select   top   3  name,age
from  taihang
order   by  age  desc

compute子句
在查询结果的末尾生成一个汇总数据行
computer
{{
avg | count | max | min | sum
(expression)} 
[ ,n ]
[ by expression [,n ] ]
avg平均值,count计算行数,max最大值,min最小值,sum求和
expression:需要统计列的名称,此列必须在select列表中且不能用别名
by  expression:查询结果中生成分类统计的行,心须同时使用order by子句,expression是对应order  by

子句中的order_by_expression的子集或全集
例:统计各个部门工资
select  name,department,wage
from  taihang
order   by  department
compute   sum (wage)  by  department