查询出各个部门中工资高于本部门的平均工资的员工数和部门号,并按部门号排序

1,创建表格 emp

2.思路:

(1)首先查询各个部门的平均工资

select detpid, avg(salary) as avgsalary 
from emp
group by detpid

在这里插入图片描述

(2)利用联合查询的思想进行查询:select * from table1,table2 where table1.name=table2.name

即把emp表与上表查询出的结果进行联合查询,找出所有工资大于平均工资的记录。

select e.* from emp as e,
(select detpid,avg(salary) as avgsalary from emp group by detpid) as b
where e.detpid=b.detpid and e.salary>b.avgsalary ; 

在这里插入图片描述

(3)查询出各个部门中工资高于本部门的平均工资的员工数和部门号,并按部门号排序

1 select e.detpid,count(*) from emp as e,
2 (select detpid,avg(salary) as avgsalary from emp group by detpid) as b
3 where e.detpid=b.detpid and e.salary>b.avgsalary 
4 group by e.detpid 
5 order by e.detpid; 

在这里插入图片描述

自己遇到的问题
1就是联合查询时“主表”没有分组,就是没有上面代码第四行,这时代码会报错。
分组的目的是为了查出符合条件的count(*)人数。

 1140 - In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'sql.e.detpid'; this is incompatible with sql_mode=only_full_group_by

2 select 后面字段中间要用 逗号 分隔开,最后一个字段 也就是from前字段不能有逗号

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值