1

我正在创建一个 SQL 查询,结果将返回他们上次参加的考试的学生考试成绩。我认为这应该相当简单,但我只是没有看到它。

这是我的测试数据

Name    Date        Score
John    2/3/2012    94
John    2/14/2012   82
John    2/28/2012   72
Mary    2/3/2012    80
Mary    2/28/2012   71
Ken     2/14/2012   68
Ken     2/14/2012   66

我希望返回的结果是

John    2/28/2012   72
Mary    2/28/2012   80
Ken     2/14/2012   66

我感谢任何帮助。

4

3 回答 3

3
select date, name, score
from temp t1
where date = (select max(date) from temp where t1.name = temp.name)

或者

SELECT a.*
FROM temp a
INNER JOIN 
(
  SELECT name,MAX(date) as max_date 
  FROM temp a
  GROUP BY name
)b ON (b.name = a.name AND a.date=b.max_date)

这是一个带有示例的sql小提琴

甚至如果您在示例数据中显示的日期对每个人都有不止一条记录,甚至会出现这种情况。

SELECT c.name,c.date, MAX(c.score) as max_score
FROM
(
 SELECT a.* 
 FROM temp a
 INNER JOIN 
 (
  SELECT name,MAX(date) as max_date 
  FROM temp a
  GROUP BY name
 )b ON (b.name = a.name AND a.date=b.max_date)
)c
group by c.name,c.date

这个例子的 Sql 小提琴

于 2012-05-09T18:01:59.537 回答
1
SELECT Name, Date, Score
FROM tablename t1
WHERE Date = (SELECT MAX(Date) 
              FROM tablename
              WHERE Name = t1.Name
              GROUP BY Name)
于 2012-05-09T18:03:34.857 回答
0

您使用的是哪个数据库?大多数支持row_number()这是回答这个问题的正确方法:

select *
from 
(
  select t.*, row_number() over (partition by name order by date desc) as seqnum
  from table t
)
where rownum = 1
于 2012-05-09T18:19:08.813 回答