SQL Show most recent record in GROUP BY?

烈酒焚心 提交于 2019-12-18 14:15:19

问题


I have a table that looks like this:

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   

I'm trying to GROUP BY SubjectCode but i'd like it to display the most recent DateApproved so it will look like:

  id    |    SubjectCode    |    Grade    |    DateApproved    |    StudentId

2            SUB123            2.00            1/5/2012            2012-12345

3            SUB123            3.00            1/5/2012            2012-98765  

I'm a little bit lost on how to do it?

EDIT:

Ok guys now im on my real PC, sorry for the poorly constructed question.

Here's what I'm actually trying to do:

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

Basically, I only want to display the most recent "DateApprove" of a "SubjectCode", so I don't get multiple entries.


回答1:


Start with this:

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

Then integrate that to main query:

select * 
from tbl
where (StudentId, DateApproved) in

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

You can also use this:

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

But I prefer tuple testing, it's way neater

Live test: http://www.sqlfiddle.com/#!2/771b8/5




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/10445162/sql-show-most-recent-record-in-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!