SQL 高级查询-count sum avg max min


聚合函数

  • count(*)
  • count()
  • sum()
  • avg()
  • max()
  • min()

count(*) 统计记录个数

  • 例1:显示职工人数
select count(*) as 职工人数 from 职工_tb
  • 例2:统计性别男,工资大于1500的职工人数
select count(*) as 男职工1500+人数 from 职工_tb where 性别='男' and 工资>=1500

count() 统计特定列个数

  • 例1:显示仓库数量
select count(仓库号) as 仓库数量 from 仓库_tb
  • 例2:显示无重复仓库数量
select count( distinct(仓库号) ) as 无重复仓库数 from 仓库_tb

tip: Oracle的count()只对number类型有效


sum()

  • 例1:显示所有职工表中工资总和
select sum(工资) as 工资和 from 职工
  • 例2:显示职工表中仓库号为wh1的工资和
select sum(工资) as 工资和 from 职工 where 仓库号='wh1'
  • 例3:职工_tb/工资_col,仓库号_col 仓库_tb/城市_col:北京,仓库号_col
    显示北京地区职工的工资和
select sum(工资) as 北京职工工资和 from 职工 where 仓库号 in(select 仓库号 from 仓库 where 城市='北京')
  • 例4:职工_tb/工资_col,仓库号_col:wh2
    显示wh2仓库的职工人数,和wh2仓库的工资和
select count(*) as 职工人数,sum(工资) as 工资和 from 职工 where 仓库号='wh2'
  • 例5:显示wh2仓库工资大于1800的职工的平均工资
select sum(工资)/count(*) as 1800+平均工资 from 职工
    where 仓库='wh2' and 工资 > 1800
  • 例6:显示工资大于平均工资的职工人数、工资和
select sum(工资) as 工资和,count(*) as 人数 from 职工
    where 工资>( sum(工资)/count(*) from 职工)

max()和min()

  • 例1:wh2仓库的职工的最大工资、最小工资、最大与最小之差
select max(工资) as 最大工资,
       min(工资) as 最小工资,
       (max(工资)-min(工资)) as 工资差
from 职工 where 仓库号='wh2'
  • 例2:工资评语,如果最大工资与最小工资之差大于300,评语为“工资差别大”,否则评语“工资差别小”
select ( max(工资)-min(工资) ) as 工资差,工资评语=
    case 
        when( max(工资)-min(工资) )>300 then '工资差别大'
        when( max(工资)-min(工资) )<300 then '工资差别小'
    end
from 职工
  • 例3:显示工资大于wh1仓库所有职工最大工资的职员信息
select * from 职工 where 工资>( sel ect max(工资) from 职工 where 仓库='wh1' )

avg()

  • 例:显示除最高和最低工资外的职工的平均工资
select avg(salary) as average_salary from employee where salary
    not in ( select max(salary) from employee ,
             select min(salary) from employee
            )

虚拟字段

  • 例1:在职工表中,显示“平均工资”虚拟字段
select *,(select avg(工资) from 职工)as 平均工资 from 职工
  • 例2:利用工资与平均工资之差作评语,值>300:差额大,值100~300:差额一般,值<100:差额小
select *,工资-(select avg(工资) from 职工) as 差值 ,评语=
case
    when abs(工资-(select avg(工资))>300 then '差额大'
    when abs(工资-(select avg(工资))>=100 then '差额一般'
    when ans(工资-(select avg(工资))<100 then '差额小'
end
from 职工
  • 例3:显示不同仓库的平均工资的虚拟字段
select *,仓库平均工资 
case 
    when 仓库号='wh1'   then (select avg(工资) from 仓库 where 仓库号='wh1')
    when 仓库号='wh2'   then (select avg(工资) from 仓库 where 仓库号='wh2')
    when 仓库号='wh3'   then (select avg(工资) from 仓库 where 仓库号='wh3')
end
from 仓库

习题

  聚合函数虚拟字段的排序

- 例1:按不同仓库的最大工资,对职工信息进行升序排序

select *,不同仓库最大工资
case
    when 仓库='wh1' then (select max(工资) from 职工 where 仓库='wh1' )
    when 仓库='wh2' then (select max(工资) from 职工 where 仓库='wh2' )
end
from 仓库
order by 不同仓库最大工资

猜你喜欢

转载自blog.csdn.net/weixin_41471128/article/details/81457614
今日推荐