Skip to content

Commit 784e0a9

Browse files
committed
what are common table expressions?
1 parent 280e51a commit 784e0a9

File tree

8 files changed

+66
-72
lines changed

8 files changed

+66
-72
lines changed

sql-queries-5/what-are-common-table-expressions/groupingby-scalar-subselect.sql

Lines changed: 0 additions & 16 deletions
This file was deleted.

sql-queries-5/what-are-common-table-expressions/recursive-cte-queries.sql

Lines changed: 0 additions & 36 deletions
This file was deleted.

sql-queries-5/what-are-common-table-expressions/substitute-for-view.sql

Lines changed: 0 additions & 20 deletions
This file was deleted.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
-- Grouping by a Column Derived from a Scalar Subselect or Non-Deterministic Function
2+
ITH AgeCategories AS (
3+
SELECT s.id AS student_id,
4+
s.name AS student_name,
5+
TIMESTAMPDIFF(YEAR, s.birth_date, s.enrollment_date) AS age_at_enrollment,
6+
CASE
7+
WHEN TIMESTAMPDIFF(YEAR, s.birth_date, s.enrollment_date) = 18 THEN '18 Years'
8+
WHEN TIMESTAMPDIFF(YEAR, s.birth_date, s.enrollment_date) = 19 THEN '19 Years'
9+
ELSE 'Above 18'
10+
END AS age_category
11+
FROM Student AS s
12+
)
13+
SELECT age_category,
14+
COUNT(student_id) AS student_count
15+
FROM AgeCategories
16+
GROUP BY age_category;
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
-- Recursive cte
2+
WITH RECURSIVE EnrollmentProgression AS (
3+
4+
SELECT
5+
id AS student_id,
6+
name,
7+
YEAR(enrollment_date) AS active_year
8+
FROM
9+
Student
10+
11+
UNION ALL
12+
13+
-- Recursive statement to increment the year until the graduation year
14+
SELECT
15+
ep.student_id,
16+
ep.name,
17+
ep.active_year + 1 AS year
18+
FROM
19+
EnrollmentProgression ep
20+
INNER JOIN
21+
student s ON ep.student_id = s.id
22+
WHERE
23+
ep.active_year < YEAR(s.graduation_date)
24+
)
25+
-- Select all active years for each student's enrollment
26+
SELECT
27+
student_id,
28+
name,
29+
active_year
30+
FROM
31+
EnrollmentProgression
32+
ORDER BY
33+
student_id, active_year
34+
LIMIT 20;
35+
36+
37+
This gives us a year-by-year breakdown of a student’s active enrollment. The table below shows all th
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
-- USING CTE as a substitute for view
2+
WITH EnrollmentStats AS (
3+
SELECT YEAR(s.enrollment_date) AS enrollment_year,
4+
AVG(s.gpa) AS average_gpa
5+
FROM Student AS s
6+
WHERE s.gpa IS NOT NULL
7+
GROUP BY YEAR(s.enrollment_date)
8+
)
9+
SELECT enrollment_year,
10+
ROUND(average_gpa,3) AS average_gpa
11+
FROM EnrollmentStats
12+
WHERE average_gpa > 3.0
13+
ORDER BY enrollment_year;

0 commit comments

Comments
 (0)