본문 바로가기

데이터베이스

DBMS - (11) sub-query[from]

DBMS - (11) sub-query[from]

<그림 1: relation example>

Q1)
select sID, sName, GPA, GPA * (sizeHS / 1000.0) as ScaledGPA
from Student
where GPA * (sizeHS / 1000.0)  - GPA > 1.0 or GPA - GPA * (sizeHS / 1000.0) > 1.0

Q2)
select sID, sName, GPA, GPA * (sizeHS / 1000.0) as ScaledGPA
from Student
where abs(GPA * (sizeHS / 1000.0)  - GPA) > 1.0

abs(=absolute) keyword로 절댓값을 사용

Q3)
select *
from (select sID, sName, GPA, GPA * (sizeHS / 1000.0) as ScaledGPA from Studnet) G
where abs(ScaledGPA - GPA) > 1.0;

from절에서 sub-query를 사용한 모습. 서브쿼리의 결과로 반환되는 릴레이션을 G keyword로 사용.
따라서, where절에서 ScaledGPA keyword를 사용할 수 있음

Q4)
select College.cName, state, GPA
from College, Apply, Student
where College.cName = Apply.cName
and Apply.sID = Student.sID
and GPA >= all ( select GPA from Student, Apply where Student.sID = Apply.sID and Apply.cName = College.cName);

Q4는 각 학교별 가장 높은 GPA를 보여준다.

Q5)
select cName, state, (select distinct GPA from Apply, Student where College.cName = Apply.cName and Student.sID = Apply.sID and GPA >= all (select GPA from Student, Apply where Student.sID = Apply.sID and Apply.cName = College.cName)) as GPA
from College

Q5는 Q4와 동일한 결과를 갖는다. select 절에서 서브쿼리를 사용할 수 있음을 보여준다.

단, Q5에서 사용한 서브쿼리의 경우 그 결과로써 반환되는 릴레이션은 반드시 degree : 1, cardinality : 1이여야만 한다.
(상위 쿼리의 attribute로 사용되므로)

Reference
https://www.youtube.com/watch?v=8OCAxk1Rybg&list=PL6hGtHedy2Z4EkgY76QOcueU8lAC4o6c3&index=14

'데이터베이스' 카테고리의 다른 글

DBMS - (13) null value  (0) 2019.08.04
DBMS - (12) aggregation function  (0) 2019.08.04
DBMS - (10) sub-query[where]: in, exists, all, any  (0) 2019.08.04
DBMS - (9) The Basic SELECT Statement  (0) 2019.07.07
DBMS - (8) Introduction to SQL  (0) 2019.07.07