-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubqueriesFromSelect.sql
74 lines (60 loc) · 2.3 KB
/
SubqueriesFromSelect.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**************************************************************
SUBQUERIES IN THE FROM AND SELECT CLAUSES
Works for MySQL and Postgres
SQLite doesn't support All
**************************************************************/
/**************************************************************
Students whose scaled GPA changes GPA by more than 1
**************************************************************/
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;
/*** Can simplify using absolute value function ***/
select sID, sName, GPA, GPA*(sizeHS/1000.0) as scaledGPA
from Student
where abs(GPA*(sizeHS/1000.0) - GPA) > 1.0;
/*** Can further simplify using subquery in From ***/
select *
from (select sID, sName, GPA, GPA*(sizeHS/1000.0) as scaledGPA
from Student) G
where abs(scaledGPA - GPA) > 1.0;
/**************************************************************
Colleges paired with the highest GPA of their applicants
**************************************************************/
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);
/*** Add Distinct to remove duplicates ***/
select distinct 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);
/*** Use subquery in Select ***/
select distinct cName, state,
(select distinct GPA
from 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)) as GPA
from College;
/*** Now pair colleges with names of their applicants
(doesn't work due to multiple rows in subquery result) ***/
select distinct cName, state,
(select distinct sName
from Apply, Student
where College.cName = Apply.cName
and Apply.sID = Student.sID) as sName
from College;