自连接返回多行

时间:2017-01-31 17:02:44

标签: postgresql

Click here to view image

请参阅附图。每个年级必须有两个标题(测试),例如Alg1 PMT1 2016-17和Alg1 PMT2 2016-17。我将根据staff_id并排显示每个test_id的结果。我试图使用自联接,但我得到重复。请帮忙

2 个答案:

答案 0 :(得分:1)

我假设您使用distinct

找到了答案

答案 1 :(得分:0)

我明白了。我使用min和max函数来隔离ID。

select distinct  x.School, x.grade, x.Teacher, x.test as Test1, x.title as Course_name, x.short_name as Course_number, x.course_period_id,  x.Students as Student, x.Number_Correct, x.Possible_Points, x.Percent_Correct,y.test as test2, y.course_period_id as course_period_id2,y.Students as Student2,y.Number_Correct as correct2, y.Possible_Points as Possible_Points2, y.Percent_Correct as Percent_Correct2, round((y.Percent_Correct)-(x.Percent_Correct)) as Grouth from final x

inner join(select distinct  School, grade, Teacher, test_id, test, short_name, Class_id, course_period_id, Students, Number_Correct, Possible_Points, Percent_Correct from final where (select max(test_id) from final) = test_id) y on ( x.course_period_id=y.course_period_id and x.grade = y.grade)
where (select MIN(test_id) from final ) = x.test_id
order by x.School,X.Teacher,x.grade,  x.course_period_id