1. 程式人生 > >mysql之多表查詢的其他查詢

mysql之多表查詢的其他查詢

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;