mysql之多表查询的其余查询

1,临时表查询spa

(1)需求:查询高于本部门平均工资的人员code

select * from person as p, (select dept_id, avg(salary) as '平均工资' from person GROUP BY dept_id) as ptable where p.dept_id = ptable.dept_id and p.salary > ptable.`平均工资`;

(2)需求:查询高于本部门平均工资的人员,显示部门名blog

第一步查询出每一个部门的平均工资,并显示部门名table

select * from (select dept_id, avg(salary) as '平均工资' from person GROUP BY dept_id) as p, dept as pd where p.dept_id = pd.did;

第二步再对每一个人的工资和第一步查询出来的结果集(让其做为临时表)的平均工资比较class

select * from person as p, (select * from (select dept_id, avg(salary) as '平均工资' from person GROUP BY dept_id) as pa, dept as pd where pa.dept_id = pd.did) as ptable where p.dept_id = ptable.dept_id and p.salary > ptable.`平均工资`;

 

2.判断查询 IF关键字select

(1)需求:根据工资高低,将人员划分为两个级别,分别为高端人群和低端人群。显示效果:姓名、年龄、性别、工资、级别im

-- IF关键字能够带三个参数,参数1条件,参数2为参数1条件成立时使用的,参数3为参数1条件不成立时使用
select p.name, p.age, p.sex, p.salary, IF(p.salary > 10000, '高端人群', '低端人群') as '级别' from person as p;

(2)需求:根据工资高低统计每一个部门人员收入状况,划分为富人、小资、平民、屌丝四个级别,要求统计四个级别分别有多少人d3

 

select dname, sum(case WHEN person.salary > 10000 THEN 1 else 0 END) as '富人', sum(case WHEN person.salary BETWEEN 5000 and 10000 THEN 1 else 0 END) as '小资', sum(case WHEN person.salary BETWEEN 3000 and 5000 THEN 1 else 0 END) as '平民', sum(case WHEN person.salary < 3000 THEN 1 else 0 END) as '屌丝'
from dept, person where dept.did = person.dept_id GROUP BY dept_id;

相关文章
相关标签/搜索