从每个组sqlite中选择前n个记录

时间:2015-01-23 21:43:01

标签: sql sqlite greatest-n-per-group

我正在尝试从数据库表结果中选择前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  

但有些科目在哪里失踪,我甚至尝试了以下链接的建议

How to select the first N rows of each group?

但是每个subjectid

我得到的更多

我做错了什么?

2 个答案:

答案 0 :(得分:8)

您可以使用相关子查询:

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

Example at SQL Fiddle.

答案 1 :(得分:4)

我希望我能正确理解你的问题。如果这是正确的,请告诉我:

我重新创建了你的桌子:

CREATE TABLE stack (
       SubjectId INTEGER(10),
       StudentId INTEGER(10),
       Levelid INTEGER(10),
       total INTEGER(10)
       )
;

插入值

INSERT INTO stack VALUES
       (1,1,1,89),
       (1,2,1,77),
       (1,3,1,61),
       (2,4,1,60),
       (2,5,1,55),
       (2,6,1,45)
;

如果您尝试通过Levelid获取顶级组(按总字段排序,假设StudentID为主键):

SELECT * 
FROM stack AS a
WHERE a.StudentID IN (
      SELECT b.StudentID
      FROM stack AS b
      WHERE a.levelid = b.levelid
      ORDER BY b.total DESC
      LIMIT 2
      )
;

产生这个结果:

SubjectId | StudentId | Levelid | total
1         | 1         | 1       | 89
1         | 2         | 1       | 77

SubjectId的前2个示例,按总计排序:

SELECT * 
FROM stack AS a
WHERE a.StudentID IN (
      SELECT b.StudentID
      FROM stack AS b
      WHERE a.subjectID = b.subjectID
      ORDER BY b.total DESC
      LIMIT 2
      )
;

结果:

SubjectId | StudentId | Levelid | total
1         | 1         | 1       | 89
1         | 2         | 1       | 77
2         | 4         | 1       | 60
2         | 5         | 1       | 55

我希望你能找到答案。