2012-05-28 213 views
2

我有麻煩試圖創建一個查詢:SQL查詢 - 動態查詢子

選擇誰沒有完成所有同行評審的某一週的所有學生。

背景:每週,每個學生必須同行評審同一組中的同齡人。

每個組都可以是不同的大小,這是我遇到的問題。

這是我目前的測試數據:

peer review table

student table

表1:同行評議表
表2:學生表。

這是我的初始查詢,根據他們所做的同行評議的數量對所有學生進行分組。我現在需要檢查,如果count(*)小於組的大小爲每個學生:

SELECT * 
FROM peerreview 
RIGHT JOIN student 
ON student. studentID = peerreview.reviewer 
WHERE week = 11 
GROUP BY studentID 
HAVING Count(*) < ???? 
+0

的 '阿凡周= 11' 位有效地把你的右連接成一個INNER JOIN。 –

+0

只是給出d表的列名和普通的id b/w他們。\ – Addicted

回答

2

下面的查詢將返回已審覈了所有的學生在同一組的學生。

SELECT a.reviewer, 
     a.groupid 
FROM (SELECT student2.studentID AS reviewer, 
       student1.groupid, 
       Count(*)   AS cnt 
     FROM student student1 
       INNER JOIN peerreview 
         ON student1.studentID = peerreview.reviewee 
       INNER JOIN STUDENT STUDENT2 
         ON student2.studentID = peerreview.reviewer 
     WHERE student2.groupid = student2.groupid 
       AND peerreview.week = 11 
     GROUP BY student1.groupid, 
        student2.studentID) a 
     INNER JOIN (SELECT groupid, 
          Count(*) - 1 AS cnt 
        FROM student 
        GROUP BY groupid) b 
       ON a.groupid = b.groupid 
        AND a.cnt = b.cnt 

See SqlFiddle

+0

mysql會拋出一個錯誤:表'student2'不存在 – dgamma3

+0

現在驗證sql。 –

+0

很好,你能解釋一下student2是什麼嗎? – dgamma3

1
Select S.StudentId As Reviewer 
    , S1.StudentId As StudentYetToBeReviewed 
    , Weeks.WeekNum 
From Student As S 
    Join Student As S1 
     On S1.GroupId = S.GroupId 
      And S1.StudentId <> S.StudentId 
    Cross Join (
       Select 7 As WeekNum 
       Union All Select 11 
       ) As Weeks 
Where Not Exists (
        Select 1 
        From PeerReview As P1 
        Where P1.reviewee = S1.StudentId 
         And P1.Week = Weeks.WeekNum 
        ) 
Order By WeekNum, reviewer 

這爲您提供一個清單,按周,審稿人,他們需要審查的人。在真正的解決方案中,您可能希望用週數的明確列表來替換交叉連接週數,在這些周內應該進行審查。

SQL Fiddle版本

0
select distinct s1.* 
    from student s1 inner join student s2 on s1.groupId = s2.groupeId 
       left join peerreview pr on pr.revieweer = s1.studentId 
        and pr.reviewee = s2.studentId 
    where pr.Week = ? and pr.revieweer is null and s1.studentId <> s2.studentId