Skip to content
Advertisement

Dynamic/Customized Week Number

Let us say there is a table which stores data for student’s attendance for classes. The student only need to attend each class once weekly. Hinging on the days_diff column, we decide which weeks the student should get credited for. As usual, each week has 7 days and the end of the week (in days) is divisible by 7. There is a different case for Week 3 in my scenario, whenever the week_3 is attended, the week ends at that attendance date and week_4 is started the next day.

I am using postgreSQL 11.4!

student_name class_subject registration_date attendance_date days_diff week_num
Frank Chemistry 2021-10-15 2021-10-18 3 week_1
Frank Chemistry 2021-10-15 2021-10-24 9 week_2
Frank Chemistry 2021-10-15 2021-11-01 17 week_3
Frank Chemistry 2021-10-15 2021-11-10 26 week_4
Frank Chemistry 2021-10-15 2021-11-20 36 week_6
Danny Physics 2021-10-20 2021-10-25 5 week_1
Danny Physics 2021-10-20 2021-11-02 13 week_2
Danny Physics 2021-10-20 2021-11-08 19 week_3
Danny Physics 2021-10-20 2021-11-23 34 week_5
Danny Physics 2021-10-20 2021-11-30 41 week_6

Desired Week Breakdown:

Requested: new_week_num column

student_name class_subject registration_date attendance_date days_diff week_num new_week_num
Frank Chemistry 2021-10-15 2021-10-18 3 week_1 week_1
Frank Chemistry 2021-10-15 2021-10-24 9 week_2 week_2
Frank Chemistry 2021-10-15 2021-11-01 17 week_3 week_3
Frank Chemistry 2021-10-15 2021-11-10 26 week_4 week_5
Frank Chemistry 2021-10-15 2021-11-20 36 week_6 week_7
Danny Physics 2021-10-20 2021-10-25 5 week_1 week_1
Danny Physics 2021-10-20 2021-11-02 13 week_2 week_2
Danny Physics 2021-10-20 2021-11-08 19 week_3 week_3
Danny Physics 2021-10-20 2021-11-23 34 week_5 week_6
Danny Physics 2021-10-20 2021-11-30 41 week_6 week_7

Advertisement

Answer

Solution 1 : cte and JOIN

Solution 2 : LATERAL JOIN

Solution 3 : window function

test in dbfiddle

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement