我有下面的表格spanishcourse,代表了西班牙语课程的学生成绩。这是一所每月开课的学校,学生可以在一年中随机开始和离开课程(分别为month in和month out专栏)。事实是,这些学生中的一些人缺课了几个月,当他们缺课时,分数是0。问题是,当学生缺席时,列month不会将成绩显示为0(列grades)。
month in month out month student grades
3 9 3 John 10
3 9 5 John 8
3 9 6 John 4
3 9 7 John 3
3 9 9 John 7
2 7 2 Mary 9
2 7 3 Mary 2
2 7 6 Mary 6
2 7 7 Mary 9
1 3 1 Jane 8
1 3 2 Jane 7
1 3 3 Jane 5
6 10 6 Rick 9
6 10 8 Rick 1
6 10 10 Rick 3 我需要的输出现在是Rick的一小部分:
month in month out month student grades
6 10 6 Rick 9
6 10 7 Rick 0
6 10 8 Rick 1
6 10 9 Rick 0
6 10 10 Rick 3 结论:我只需要添加从学生开始到结束的缺失句号。考虑到Rick的例子,我们只添加了7个月和9个月作为0级。你们中的一些人能帮我一下吗?
附言:我已经看到了一些其他的回答问题。他们是相反的,因为他们把从1到n的所有数据都考虑在内,而不是像这个例子那样考虑随机月份。
发布于 2014-07-11 23:24:31
您可以使用cross join和left outer join来完成此操作。cross join生成学生和月份之间的所有组合。left outer join为匹配的记录引入数据。不匹配的记录将获得0等级。
下面假设某个学生在每个月都有一个成绩:
select s.month_in, s.month_out, m.month, s.student,
coalesce(sc.grades, 0) as grades
from (select distinct student, month_in, month_out from spanishcourse sc) s cross join
(select distinct month from spanishcourse sc) m left outer join
spanishcourse sc
on sc.student = s.student and sc.month = m.month;发布于 2014-07-11 23:29:20
SQL Fiddle
select s.month_in, s.month_out, month, student, coalesce(grades, 0)
from
spanishcourse sc
right join
(
select distinct
student, month_in, month_out,
generate_series(month_in, month_out, 1) as month
from spanishcourse
) s using (student, month)
order by student, monthhttps://stackoverflow.com/questions/24700863
复制相似问题