1,临时表查询
(1)需求:查询高于本部门平均工资的人员
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)需求:查询高于本部门平均工资的人员,显示部门名
第一步查询出每个部门的平均工资,并显示部门名
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;
第二步再对每个人的工资和第一步查询出来的结果集(让其作为临时表)的平均工资比较
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关键字
(1)需求:根据工资高低,将人员划分为两个级别,分别为高端人群和低端人群。显示效果:姓名、年龄、性别、工资、级别
-- 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)需求:根据工资高低统计每个部门人员收入情况,划分为富人、小资、平民、屌丝四个级别,要求统计四个级别分别有多少人
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;