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;