2014-02-05 143 views
2

我需要MS-Access中的一個查詢,它將返回到每個學生完成的課程的最後一個。數據看起來是這樣的:如何獲得每個主記錄的最後2個細節?

學生

ID | StudentName 
1  John 
2  Bill 
3  Ted 
4  Edward 

TrainingDetails

ID | StudentID | ClassName | Date 
    1  1   Math  10/10/2012 
    2  1   Science  12/10/2012 
    3  2   Math  10/10/2012 
    4  3   Math  10/10/2012 
    5  2   Art   09/10/2012 
    6  2   History  02/10/2012 
    7  3   Science  12/10/2012 
    8  3   History  02/10/2012 
    9  4   Music  12/10/2012 

所需的輸出

Name | Class  | Date 
John  Science  12/10/2012 
John  Math  10/10/2012 
Bill  Math  10/10/2012 
Bill  Art   09/10/2012 
Ted  Science  12/10/2012 
Ted  Math  10/10/2012 
Edward Music  12/10/2012 

我使用SELECT TOP 2條款試過,但我只得到2記錄總數。我想我需要一些循環來獲得每個學生,然後每個學生的前2條記錄,但我不能在一個查詢中得到它。

回答

1

嘗試下面的查詢。我有一個與SQLServer fiddle工作,但應該爲Access工作。您可以根據需要訂購結果。

SELECT s.StudentName, t.classname, t.date 
FROM Students s 
    INNER JOIN TrainingDetails t ON t.StudentID = s.id 
WHERE t.Date in (SELECT TOP 2 t2.Date 
       FROM TrainingDetails t2 
       WHERE t2.StudentID = s.ID 
       ORDER BY t2.Date DESC) 

(代碼修正與存取SQL工作。)

1

如果我們用一個自聯接查詢,我們可以指定一個等級的各種班每個學生(1 =最新):

SELECT 
    t1.StudentID, 
    t1.ClassName, 
    t1.Date, 
    COUNT(*) AS Rank 
FROM 
    TrainingDetails AS t1 
    INNER JOIN 
    TrainingDetails AS t2 
     ON t2.StudentID = t1.StudentID 
      AND t2.Date >= t1.Date 
GROUP BY 
    t1.StudentID, 
    t1.ClassName, 
    t1.Date 
ORDER BY 1, 4 

返回

StudentID ClassName Date  Rank 
--------- --------- ---------- ---- 
     1 Science 2012-12-10  1 
     1 Math  2012-10-10  2 
     2 Math  2012-10-10  1 
     2 Art  2012-09-10  2 
     2 History 2012-02-10  3 
     3 Science 2012-12-10  1 
     3 Math  2012-10-10  2 
     3 History 2012-02-10  3 
     4 Music  2012-12-10  1 

我們可以與[學生]一起獲取名稱,並將結果限制爲WHERE Rank <= 2

返回

StudentName ClassName Date  Rank 
----------- --------- ---------- ---- 
John   Science 2012-12-10  1 
John   Math  2012-10-10  2 
Bill   Math  2012-10-10  1 
Bill   Art  2012-09-10  2 
Ted   Science 2012-12-10  1 
Ted   Math  2012-10-10  2 
Edward  Music  2012-12-10  1 
相關問題