sql GROUP BY但是使用最新的记录?

时间:2012-05-04 09:48:06

标签: group-by sql-order-by

我正在尝试做这样的事情,我不确定是否可以使用简单的GROUP BY:

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

所以当我有这样一张桌子时:

学生:2012-12345

SubjectCode | Grade | DateApproved
SUBJ123 | 2.00 | 1/4/2012
SUBJ123 | 1.75 | 1/5/2012
SUBJ987 | 1.50 | 1/5/2012

它应该是这样的:

学生:2012-12345

SubjectCode | Grade | DateApproved
SUBJ123 | 1.75 | 1/5/2012
SUBJ987 | 1.50 | 1/5/2012

编辑:这是解决方案:

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='2011-10172' AND 
    NOT EXISTS (
        SELECT 1 FROM gradebook G2 INNER JOIN gradebookdetail GD2 ON G2.GradebookId=GD2.GradebookId
        WHERE 
            G2.GradebookType = 'final' AND 
            G2.DateApproved IS NOT NULL AND 
            GD2.StudentIdNumber = GD.StudentIdNumber AND 
            G2.SubjectCode = G.SubjectCode AND
            G2.DateApproved > G.DateApproved
    )
ORDER BY G.SubjectCode ASC

1 个答案:

答案 0 :(得分:1)

我认为这个查询会做你想要的,但我还没有测试过。如果有问题,请告诉我。

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' AND 
    NOT EXISTS (
        SELECT 1 FROM gradebook G2 
        WHERE 
            G2.GradebookType = 'final' AND 
            G2.DateApproved IS NOT NULL AND 
            G2.StudentIdNumber = G.StudentIdNumber AND 
            G2.StudentCode = G.SubjectCode AND
            G2.DateApproved > G.DateApproved
    )
ORDER BY G.SubjectCode ASC