-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathCTE Lesson.sql
78 lines (73 loc) · 1.45 KB
/
CTE Lesson.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
75
76
77
78
/*
SQL Course - CTE Lesson
CTE - Common Table Expression, uses the WITH clause
*/
/*
Two (or more step) processes are tricky when we have to write everything in one statement
One option is a simple subquery approach
Note that this approach may becomes unreadable if there are several levels of nesting
*/
SELECT
p.AdmittedDate
, p.AdvancedTariff
FROM
(
SELECT
ps.AdmittedDate
, ps.Hospital
, SUM(ps.Tariff) + 1 AS AdvancedTariff
FROM
PatientStay ps
GROUP BY
ps.AdmittedDate
, ps.Hospital) p
WHERE
p.Hospital = 'PRUH'
AND p.AdvancedTariff > 5;
/*
Use WITH and a common table expression (CTE)
This yields exactly the same result but is more readable.
NOTE: SQL needs to know that WITH is the start of a statement - the previous statement must have a semi-colon at end
*/
WITH p (AdmittedDate, Hospital, AdvancedTariff)
AS (
SELECT
ps.AdmittedDate
, ps.Hospital
, SUM(ps.Tariff) + 1
FROM
PatientStay ps
GROUP BY
ps.AdmittedDate
, ps.Hospital)
SELECT
p.AdmittedDate
, p.AdvancedTariff
FROM
p
WHERE
p.Hospital = 'PRUH'
AND p.AdvancedTariff > 5;
/*
We can also write this without the column list in the CTE as long as all the columns
within the CTE definition have a column name or alias.
*/
WITH p
AS (
SELECT
ps.AdmittedDate
, ps.Hospital
, SUM(ps.Tariff) + 1 AS AdvancedTariff
FROM
PatientStay ps
GROUP BY
ps.AdmittedDate
, ps.Hospital)
SELECT
p.AdmittedDate
, p.AdvancedTariff
FROM
p
WHERE
p.Hospital = 'PRUH'
AND p.AdvancedTariff > 5;