Skip to content

Commit 0f277a2

Browse files
committed
find_students_with_study_spiral_pattern.sql
1 parent 0d16b1d commit 0f277a2

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
-- Write your PostgreSQL query statement below
2+
WITH cte AS (
3+
SELECT
4+
student_id,
5+
COUNT(DISTINCT subject) cycle_length,
6+
SUM(hours_studied) total_study_hours,
7+
COUNT(1) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) cnt
8+
FROM (
9+
SELECT
10+
student_id,
11+
subject,
12+
hours_studied,
13+
session_date::date - (LAG(session_date, 1, session_date)
14+
OVER (PARTITION BY student_id ORDER BY session_date))::date date_diff
15+
FROM study_sessions)
16+
GROUP BY student_id
17+
HAVING MAX(date_diff) <= 2
18+
AND COUNT(DISTINCT subject) >= 3
19+
AND COUNT(subject) / COUNT(DISTINCT subject) >= 2)
20+
SELECT
21+
student_id,
22+
student_name,
23+
major,
24+
cycle_length,
25+
total_study_hours
26+
FROM cte
27+
LEFT JOIN students USING (student_id)
28+
WHERE cnt > 1
29+
ORDER BY cycle_length DESC, total_study_hours DESC

0 commit comments

Comments
 (0)