需求:查询员工中工资大于本部门平均工资的员工的last_name,salary和其department_id

    1. # 方式1:使用相关子查询
    2. SELECT last_name,salary,department_id
    3. FROM employees e1
    4. WHERE salary > (
    5. SELECT AVG(salary)
    6. FROM employees e2
    7. WHERE department_id = e1.`department_id`
    8. );
    9. #方式2:在FROM中声明子查询
    10. SELECT e.last_name,e.salary,e.department_id
    11. FROM employees e,(
    12. SELECT department_id,AVG(salary) avg_sal
    13. FROM employees
    14. GROUP BY department_id) t_dept_avg_sal
    15. WHERE e.department_id = t_dept_avg_sal.department_id
    16. AND e.salary > t_dept_avg_sal.avg_sal;

    需求:查询员工的id,salary,按照department_name 排序

    1. SELECT employee_id,salary
    2. FROM employees e
    3. ORDER BY (
    4. SELECT department_name
    5. FROM departments d
    6. WHERE e.`department_id` = d.`department_id`
    7. ) ASC;

    需求:
    若employees表中employee_id与job_history表中employee_id相同的数目不小于2,输出这些相同id的员工的employee_id,last_name和其job_id

    1. SELECT employee_id,last_name,job_id
    2. FROM employees e
    3. WHERE 2 <= (
    4. SELECT COUNT(*)
    5. FROM job_history j
    6. WHERE e.`employee_id` = j.`employee_id`
    7. );