而不是只盯着学期的长度或它们之间的差距,可以产生都是一个学期之内,使用日期的列表
generate_series(),像这样:
SELECt row_number() OVER () as day_number, dayFROM( SELECt generate_series(start_date, end_date, '1 day') as day FROM semesters) as day_seriesORDER BY day
(SQLFiddle演示)
这会为一个学期中的每一天分配一个任意但连续的“天数”,从而跳过了两个学期之间的所有间隔。
然后,您可以将其用作学生表的子查询/
CTE
JOIN:首先找到他们开始日期的“天数”,然后添加
7 * n_weeks以找到他们结束日期的“天数”,最后加入到查找该“天数”的实际日期。
假设在半周内无需进行特殊处理-即如果
n_weeks为4,则必须在第二学期内注册28天的学生。可以采用这种方法来测量周数(
1week作为的最后一个参数传递
generate_series()),另外还可以找到学生
start_date属于哪一周。
这是一个完整的查询(此处为SQLFiddle演示):
WITH semester_days AS( SELECt semester_id, row_number() OVER () as day_number, day_date::date FROM ( SELECt id as semester_id, generate_series(start_date, end_date, '1 day') as day_date FROM semesters ) as day_series ORDER BY day_date)SELECt S.id as student_id, S.start_date, SD_start.semester_id as start_semester_id, S.n_weeks, SD_end.day_date as end_date, SD_end.semester_id as end_semester_idFROM students as SJOIN semester_days as SD_start On SD_start.day_date = S.start_dateJOIN semester_days as SD_end On SD_end.day_number = SD_start.day_number + (7 * S.n_weeks)ORDER BY S.start_date
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)