forked from AlexTheAnalyst/SQL-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubquery Tutorial.sql
43 lines (29 loc) · 916 Bytes
/
Subquery Tutorial.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
/*
Today's Topic: Subqueries (in the Select, From, and Where Statement)
*/
Select EmployeeID, JobTitle, Salary
From EmployeeSalary
-- Subquery in Select
Select EmployeeID, Salary, (Select AVG(Salary) From EmployeeSalary) as AllAvgSalary
From EmployeeSalary
-- How to do it with Partition By
Select EmployeeID, Salary, AVG(Salary) over () as AllAvgSalary
From EmployeeSalary
-- Why Group By doesn't work
Select EmployeeID, Salary, AVG(Salary) as AllAvgSalary
From EmployeeSalary
Group By EmployeeID, Salary
order by EmployeeID
-- Subquery in From
Select a.EmployeeID, AllAvgSalary
From
(Select EmployeeID, Salary, AVG(Salary) over () as AllAvgSalary
From EmployeeSalary) a
Order by a.EmployeeID
-- Subquery in Where
Select EmployeeID, JobTitle, Salary
From EmployeeSalary
where EmployeeID in (
Select EmployeeID
From EmployeeDemographics
where Age > 30)