27

我有一个看起来像这样的表:

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

4 回答 4

37

从这个开始:

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)

但我更喜欢元组测试,它更整洁

现场测试:http ://www.sqlfiddle.com/#!2/771b8/5

于 2012-05-04T08:39:56.053 回答
9
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
于 2012-05-04T08:46:04.933 回答
0
SELECT *
FROM TheTable a
WHERE NOT EXISTS(SELECT *
                 FROM TheTable b
                 WHERE b.StudentCode = a.StudentCode AND b.DateApproved > a.DateApproved)
于 2012-05-04T08:31:37.413 回答
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
)
于 2020-07-14T05:37:22.957 回答