mysql 是否在GROUP BY中显示最近的记录?

sqyvllje  于 2023-02-07  发布在  Mysql
关注(0)|答案(6)|浏览(169)

我有一个类似这样的表:

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

我正在尝试按主题代码分组,但我希望它显示最近的批准日期,因此它看起来像:

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",所以我不会得到多个条目。

oymdgrw7

oymdgrw71#

从这个开始:

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

oxf4rvwz

oxf4rvwz2#

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
cqoc49vn

cqoc49vn3#

对于在SQL Server中尝试此操作的用户,在撰写本文时(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
)
3zwjbxry

3zwjbxry4#

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

lndjwyie5#

这对我在postgres更有效率。

select * from tbl t1 where t1.DateApproved = (select max(t2.DateApproved) from tbl t2 where t2.StudentId = t1.StudentId)
kx7yvsdv

kx7yvsdv6#

此代码适用于SQL Server 2016。
从按学生ID分组的表中选择学生ID,最大值(批准日期)
此代码将显示每个学生ID批准的最大和最小日期。
选择学生ID、最大值(批准日期)、最小值(批准日期)
按学生ID从表组

相关问题