我有一个学生数据库。
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 |