2013-01-08 50 views
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

看到這個樣本數據似乎有一個趨勢,有人蔘加主觀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  | 

回答

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

+0

謝謝,當我將它放入sqlfiddle時,出現了一些錯誤,我不確定它們是否只是語法錯誤? 「字段列表」中的未知列'cl2id'我認爲這需要更改爲cl2.id? 'where clause'中的未知列'cl1.studentid'我不確定cl1來自哪裏?所以我改變了這個cl? 「字段列表」中的未知列'students.studentid':我無法弄清楚爲什麼會發生這種情況? – ak85

+0

毫無疑問,SQL小提琴。如果你在SQL Fiddle中設置它,最好包含一個鏈接。例如,一個問題是子查詢中的「cl2id」而不是「cl2.id」。 –

+0

我更新了語法錯誤,因此它現在可以在您插入SQL小提琴時起作用。我還添加了absentnext,這樣你就可以看到他們什麼時候缺席。感謝您的大力幫助! – ak85

0

一個快速和骯髒的解決辦法是讓Classlist.Id所有線路,其中subjectid = 4(讓我們N通話它們),然後選擇所有行其中Id = N +1

相關問題