我试图从看起来像这样的数据库表结果中选择前2条记录
SubjectId | StudentId | Levelid | total ------------------------------------------ 1 | 1 | 1 | 89 1 | 2 | 1 | 77 1 | 3 | 1 | 61 2 | 4 | 1 | 60 2 | 5 | 1 | 55 2 | 6 | 1 | 45
我试过这个查询
SELECT rv.subjectid, rv.total, rv.Studentid, rv.levelid FROM ResultView rv LEFT JOIN ResultView rv2 ON ( rv.subjectid = rv2.subjectid AND rv.total <= rv2.total ) GROUP BY rv.subjectid, rv.total, rv.Studentid HAVING COUNT( * ) <= 2 order by rv.subjectid desc
但是有些主题,例如失踪的地方,我什至尝试了以下链接的建议
但是我为每个受检者得到两个以上
我究竟做错了什么?
您可以使用相关的子查询:
select * from ResultView rv1 where SubjectId || '-' || StudentId || '-' || LevelId in ( select SubjectId || '-' || StudentId || '-' || LevelId from ResultView rv2 where SubjectID = rv1.SubjectID order by total desc limit 2 )
该查询通过串联三列来构造单列主键。如果您有真正的主键(如ResultViewID),则可以用代替SubjectId || '-' ||StudentId || '-' || LevelId。
ResultViewID
SubjectId || '-' ||StudentId || '-' || LevelId
SQL Fiddle中的示例。