2012-05-04 76 views
14

我有一個表,看起來像這樣:SQL顯示GROUP BY中的最新記錄?

id | SubjectCode | Grade | DateApproved | StudentId 

1   SUB123   1.25   1/4/2012   2012-12345 

2   SUB123   2.00   1/5/2012   2012-12345 

3   SUB123   3.00   1/5/2012   2012-98765 

我想GROUP BY SubjectCode,但我想它顯示最近DateApproved所以它看起來像:

id | SubjectCode | Grade | DateApproved | StudentId 

2   SUB123   2.00   1/5/2012   2012-12345 

3   SUB123   3.00   1/5/2012   2012-98765 

如何做到我有點失落?

編輯:

玉傢伙現在即時通訊我真正的PC上,比較遺憾的是結構不佳的問題。

這裏就是我真正想要做的事:

SELECT GD.GradebookDetailId, G.SubjectCode, G.Description, G.UnitsAcademic, G.UnitsNonAcademic, 
GD.Grade, GD.Remarks, G.FacultyName, STR_TO_DATE(G.DateApproved, '%m/%d/%Y %h:%i:%s') AS 'DateAproved' 
FROM gradebookdetail GD INNER JOIN gradebook G ON GD.GradebookId=G.GradebookId 
WHERE G.DateApproved IS NOT NULL AND G.GradebookType='final' AND StudentIdNumber='2012-12345' 

GROUP BY <?????> 
ORDER BY G.SubjectCode ASC 

基本上,我只是想顯示「SubjectCode」的最近「DateApprove」,所以我沒有得到多個條目。

+0

你真的想按StudentId。做到這一點的方法是選擇max(DateApproved)。 (假設DateApproved是一個日期字段) –

+0

Ok,DateApproved是一個VARCHAR,這個工作:MAX(STR_TO_DATE(DateApproved,'%d%m%y'))? –

+0

嗯。我猜想值得一試。你必須嘗試看看。我不太熟悉mysql語法。 –

回答

0
SELECT * 
FROM TheTable a 
WHERE NOT EXISTS(SELECT * 
       FROM TheTable b 
       WHERE b.StudentCode = a.StudentCode AND b.DateApproved > a.DateApproved) 
25

開始與此:

select StudentId, max(DateApproved) 
from tbl 
group by StudentId 

然後集成了主查詢:

select * 
from tbl 
where (StudentId, DateApproved) in 

(
    select StudentId, max(DateApproved) 
    from tbl 
    group by StudentId 
) 

您也可以使用此:

select * 
from tbl 
join (select StudentId, max(DateApproved) as DateApproved 
     from tbl 
     group by StudentId) 
using (StudentId, DateApproved) 

但我更喜歡的元組測試,它的方式neater

現場測試:http://www.sqlfiddle.com/#!2/771b8/5

7
SELECT t2.* 
FROM temp t2 
INNER JOIN(
    SELECT MAX(DateApproved) as MaxDate, StudentId 
    FROM temp 
    GROUP BY StudentId 
    ) t1 ON t1.MaxDate = t2.DateApproved and t1.StudentId = t2.StudentId 
+0

H可能需要'GROUP BY StudentId,SubjectCode'(並適當地改變'ON'條件)。但這是要走的路。 –