--子查詢(單列,單列只回傳一個資料,若可回傳資料超過一個則出現錯誤)
常見錯誤:回傳值超過一個、子查詢未找到符合條件者故沒有回傳資料
--<>:not equal to
--誰的薪水比abel多?
select LAST_NAME
from EMPLOYEES
where salary>(select SALARY from EMPLOYEES where LAST_NAME='Abel')--1.括弧內尋找Abel的薪水
----2.括弧外設定尋找條件為薪水大於括弧內所得出數字
LAST_NAME |
King |
Kochhar |
De Haan |
Hartstein |
Higgins |
--誰的薪水最低?
select LAST_NAME
from EMPLOYEES
where salary=(select min(salary) from EMPLOYEES)
LAST_NAME |
Vargas |
--查詢各部門最低薪水
select DEPARTMENT_ID,min(salary)
from EMPLOYEES
group by DEPARTMENT_ID
DEPARTMENT_ID | min |
NULL | 7000 |
10 | 4400 |
20 | 6000 |
50 | 2500 |
60 | 4200 |
80 | 8600 |
90 | 17000 |
110 | 8300 |
--查詢大於"部門ID110"最低薪水的各部門最低薪水
(也就是最低薪資大於8300的各部門)
select DEPARTMENT_ID,min(salary)min
from EMPLOYEES
group by DEPARTMENT_ID--以部門分組,分組用having而非where
having min(salary)>(select min(salary) from EMPLOYEES where DEPARTMENT_ID=110)--括弧內找出部門ID110中的最低薪水
DEPARTMENT_ID | min |
80 | 8600 |
90 | 17000 |
--子查詢(多列)
--找出所有薪水比IT人員最高薪少的員工,不可是IT人員者
select LAST_NAME,SALARY,job_id
from EMPLOYEES
where salary<any(select SALARY
from EMPLOYEES
where JOB_ID='IT_PROG')--括號內為所有IT員工的薪資,括號外要求需要小於任何一個,所以至少要小於最大的(9000)
and job_id <> 'IT_PROG';--不要IT人員
LAST_NAME | SALARY | job_id |
Mourgos | 5800 | ST_MAN |
Rajs | 3500 | ST_CLERK |
Davies | 3100 | ST_CLERK |
Matos | 2600 | ST_CLERK |
Vargas | 2500 | ST_CLERK |
Taylor | 8600 | SA_REP |
Grant | 7000 | SA_REP |
Whalen | 4400 | AD_ASST |
Fay | 6000 | MK_REP |
Gietz | 8300 | AC_ACCOUNT |
--找出所有薪水比IT人員最低薪少的員工,不可是IT人員者
select LAST_NAME,SALARY,job_id
from EMPLOYEES
where salary<all(select SALARY
from EMPLOYEES
where JOB_ID='IT_PROG')--括號內為所有IT員工的薪資,括號外要求需要小於所有IT,所以至少要小於最小的(4200)
and job_id <> 'IT_PROG';
LAST_NAME | SALARY | job_id |
Rajs | 3500 | ST_CLERK |
Davies | 3100 | ST_CLERK |
Matos | 2600 | ST_CLERK |
Vargas | 2500 | ST_CLERK |
--找出非主管職的員工
select e.LAST_NAME
from EMPLOYEES e
where e.EMPLOYEE_ID not in ( select m.MANAGER_ID from EMPLOYEES m)--找出所有主管的ID,因為有主管的ID是null,所以回傳會失敗
select m.MANAGER_ID from EMPLOYEES m:
MANAGER_ID |
NULL |
100 |
100 |
100 |
100 |
100 |
101 |
101 |
102 |
103 |
103 |
124 |
124 |
124 |
124 |
149 |
149 |
149 |
201 |
205 |
改寫:
--找出非主管職的員工
select e.LAST_NAME
from EMPLOYEES e
where e.EMPLOYEE_ID not in ( select m.MANAGER_ID from EMPLOYEES m where m.MANAGER_ID is not null)
LAST_NAME |
Ernst |
Lorentz |
Rajs |
Davies |
Matos |
Vargas |
Abel |
Taylor |
Grant |
Whalen |
Fay |
Gietz |
留言列表