1

我有一个学生数据库。

    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

从这个样本数据来看,似乎有一种趋势,即在某人参加了 subjectid 4 之后,他们通常不会来下一堂课。如何在查询中捕获这一点。我只想显示最后一个 subjectid = 4 的数据。因此,在我的示例数据行中,符合我的标准。

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

因为这些行都是 subjectid=4 的学生 ID 的下一行。

我的输出是

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

2 回答 2

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

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

我修复了查询。SQLFiddle 是k

于 2013-01-08T14:45:53.090 回答
0

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

于 2013-01-08T10:37:36.763 回答