SQL 分组查询

tip:分组之前的条件用where,分组之后的条件用having

group by

  • 例1:显示不同仓库的仓库号和平均工资
select 仓库号,avg(工资)  as 仓库平均工资 from 职工 group by 仓库号
  • 例2:显示工资大于wh1仓库的平均工资、性别不为空的不同仓库的仓库号和平均工资
select 仓库号,avg(工资) as 仓库平均工资 from 职工
    where 性别 is not null and 
        ( 工资>( select avg(工资) from 职工 where 仓库号='wh1' ) )
group by 仓库号

having

  • 例1:显示平均工资大于1700的不同仓库的仓库号和平均工资
select 仓库号,avg(工资) as 平均工资 from 职工
    group by 仓库号 having avg(工资)>1700
  • 例2:where+having:显示姓名中不含“刘”字、最大工资与最小工资之差大于350的不同仓库的仓库号、最大工资、最小工资、最大于最小工资之差
select 仓库号,max(工资) as 最大工资,min(工资) as 最小工资,max(工资)-min(工资) asfrom 职工
       where 姓名 not like '%刘%' 
       group by 仓库号 
       having (max(工资)-min(工资)>350)

多列组合

  • 例1:显示性别不为空、工资不大于2100、并按性别和仓库号分组的职工的平均工资
select 性别,仓库号,avg(工资) from 职工 
    where 性别 is mot null and 工资!>2100
    group by 性别,仓库号

all

group by all a,b

tip:有where才有意义
查询结果包含不符合搜索条件的行

例:显示含性别为null的结果

select 性别,仓库号,avg(工资) from 职工 
    where 性别 is mot null and 工资!>2100
    group by all 性别,仓库号  

cube

group by a,b with cube

如果Group by(a,b,c) with cube
那么分组计算时可分为如下几种分组:
(a,b,c),(a,b),(b,c),(a,c),(a),(b),(c),()。

例:显示仓库号为NULL的结果

select 仓库号,性别,avg(工资) from 职工 
    where 性别 is mot null and 工资!>2100
    group by 仓库号 with cube 

roolup

group by roolup(字段1,字段2) 或者 group by (字段1,字段2) with roolup

只对某一层次聚合
ROLLUP会根据GROUP BY后面的字段从右到左逐步以去掉右边一个字段,逐步向上累计求和。
分组:(ID,CODE),(ID),()

例:先对仓库号排序,显示含性别为null的结果

select 仓库号,性别,avg(工资) from 职工 
    where 性别 is mot null and 工资!>2100
    group by 仓库号,性别, with roolup

分组查询的排序

group by xx order by xx

compute

例:姓名含“刘”的职工信息,及汇总信息

select * from 职工 where 姓名 like '%刘%'
    compute avg(工资),max(工资),min(工资),sum(工资),count(工资)

tip:会显示两张表,*和cumpute

compute by

tip:必须同时使用order by
例:显示不同仓库职工信息,及职工汇总

扫描二维码关注公众号,回复: 2841773 查看本文章
select * from 职工 order by 仓库号
    compute avg(工资),max(工资),min(工资),sum(工资),count(工资) by 仓库号

tip:会按仓库号分别显示每个仓库的*信息和汇总信息

猜你喜欢

转载自blog.csdn.net/weixin_41471128/article/details/81457633