我有一個學生數據庫。根據表中前一行的結果選擇數據
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最後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 |
謝謝,當我將它放入sqlfiddle時,出現了一些錯誤,我不確定它們是否只是語法錯誤? 「字段列表」中的未知列'cl2id'我認爲這需要更改爲cl2.id? 'where clause'中的未知列'cl1.studentid'我不確定cl1來自哪裏?所以我改變了這個cl? 「字段列表」中的未知列'students.studentid':我無法弄清楚爲什麼會發生這種情況? – ak85
毫無疑問,SQL小提琴。如果你在SQL Fiddle中設置它,最好包含一個鏈接。例如,一個問題是子查詢中的「cl2id」而不是「cl2.id」。 –
我更新了語法錯誤,因此它現在可以在您插入SQL小提琴時起作用。我還添加了absentnext,這樣你就可以看到他們什麼時候缺席。感謝您的大力幫助! – ak85