根据表中前一行的结果选择数据

时间:2013-01-08 10:28:04

标签: mysql select

我有一个学生数据库。

    CREATE TABLE classlist
        (`id` int, `studentid` int, `subjectid` int, `presentid` int)
    ;

    CREATE TABLE student
        (`id` int, `name` varchar(4))
    ;

    CREATE TABLE subject
        (`id` int, `name` varchar(4))
    ;

    CREATE TABLE classStatus
        (`id` int, `name` varchar(8))
    ;

    INSERT INTO classlist
        (`id`, `studentid`, `subjectid`, `presentid`)
    VALUES
        (1, 111, 1, 1),
        (2, 222, 3, 0),
        (3, 333, 2, 1),
        (4, 111, 4, 1),
        (5, 111, 1, 0),
        (6, 222, 3, 0),
        (7, 333, 2, 1),
        (8, 111, 4, 1),
        (9, 111, 2, 0),
        (10, 111, 4, 1),
        (11, 111, 1, 1),
        (12, 333, 3, 1),
        (13, 333, 2, 1),
        (14, 333, 3, 1)
    ;

    INSERT INTO student
        (`id`, `name`)
    VALUES
    (111, 'John'),
    (222, 'Kate'),
    (333, 'Matt')
    ;

    INSERT INTO subject
        (`id`, `name`)
    VALUES
    (1, 'MATH'),
    (2, 'ENG'),
    (3, 'SCI'),
    (4, 'GEO')
    ;

    INSERT INTO classStatus
        (`id`, `name`)
    VALUES
    (0, 'Absent'),
    (1, 'Present')
    ;

我有一个查询,显示他们出现或缺席的次数。

    SELECT
       studentid,
       students.name AS NAME,
       SUM(presentid = 1) AS present,
       SUM(presentid = 0) AS absent

    FROM classlist
    INNER JOIN student as students ON classlist.studentid=students.id

     GROUP BY studentid, NAME

请看下面这个小提琴。 http://sqlfiddle.com/#!2/fe0b0/1

从这个样本数据来看似乎有一种趋势,即在有人参加主题4后,他们往往没有进入下一堂课。如何在查询中捕获它。我想只显示数据WHERE last subjectid = 4。因此,在我的样本数据中,符合我标准的行将是。

    (5, 111, 1, 0),
    (9, 111, 2, 0),
    (11, 111, 1, 1),

因为这些行都是具有subjectid = 4的studentid的下一行。

我的输出是

    | STUDENTID | NAME | PRESENT    | ABSENT|
    | 111       | John | 1          | 2     |

2 个答案:

答案 0 :(得分:1)

要获得学生的下一堂课,请使用相关的子查询:

select cl.*,
       (select min(cl2.id) from classlist cl2 where cl2.studentid = cl.studentid and cl2.id > cl.id) as nextcl
from classlist cl

将此插入您的查询示例会告诉您下一堂课的出席和缺席情况:

SELECT students.id, students.name AS NAME,
       SUM(cl.presentid = 1) AS present, SUM(cl.presentid = 0) AS absent,
       sum(clnext.presentid = 1) as presentnext
FROM (select cl.*,
             (select min(cl2.id) from classlist cl2 where cl2.studentid = cl.studentid and cl2.id > cl.id) as nextcl
      from classlist cl
     ) cl INNER JOIN
     student as students
     ON cl.studentid = students.id left outer join
     classlist clnext
     on cl.nextcl = clnext.id
 GROUP BY students.id, students.NAME

添加where cl.subjectid = 4以获得主题4的答案。

我修复了查询。 SQLFiddle是k

答案 1 :(得分:0)

一个快速而肮脏的解决方案可能是获取所有行的Classlist.Id,其中subjectid = 4(让我们称之为n)然后选择Id = n + 1

的所有行