SQL显示GROUP BY中的最新记录?

时间:2012-05-04 08:17:12

标签: mysql sql group-by sql-order-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  

我对如何去做有点迷失?

编辑:

好的家伙现在我在我真正的电脑上,抱歉这个构造不好的问题。

以下是我实际上要做的事情:

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”,所以我没有多次输入。

4 个答案:

答案 0 :(得分:27)

从这开始:

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

答案 1 :(得分: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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

对于在撰写本文(2020年)时仍不支持元组的SQL Server中尝试此操作的用户,则可以使用以下内容(在此处改善另一个答案)

更改此:

-- MYSQL
select * 
from tbl
where (StudentId, DateApproved) in
(
  select StudentId, max(DateApproved) 
  from tbl
  group by StudentId
)

对此:

-- Microsoft SQL Server
select * 
from tbl
where concat(StudentId, DateApproved) in
(
  select concat(StudentId, max(DateApproved)) 
  from tbl
  group by StudentId
)