Sql 在MS Access中查找最大值并显示不同字段中的相应值
所以我在()找到了类似的问题和答案,但我想更进一步。我想得到每个ID和相应类型的最新日期,而不是所有条目的绝对最大值。有什么建议吗Sql 在MS Access中查找最大值并显示不同字段中的相应值,sql,ms-access,max,greatest-n-per-group,corresponding-records,Sql,Ms Access,Max,Greatest N Per Group,Corresponding Records,所以我在()找到了类似的问题和答案,但我想更进一步。我想得到每个ID和相应类型的最新日期,而不是所有条目的绝对最大值。有什么建议吗 ID Type Date 1 Initial 1/5/15 1 Periodic 3/5/15 2 Initial 2/5/15 3 Initial 1/10/15 3 Periodic 3/6/15 4 Initi
ID Type Date
1 Initial 1/5/15
1 Periodic 3/5/15
2 Initial 2/5/15
3 Initial 1/10/15
3 Periodic 3/6/15
4 Initial 3/8/15
下面的代码显示了如何只获取所有条目的最大日期,但我需要每个ID的最大日期,然后是相应的类型
select id, type, date
from yourtable
where date in (select max(date)
from yourtable)
或
可以对相关子查询使用第一个方法:
select id, type, date
from yourtable as t
where date in (select max(date)
from yourtable as t2
where t2.id = t.id);
或者,在第二个字段中按id
分组:
select t1.id, t1.type, t1.date
from yourtable as t1 inner join
(select id, max(date) maxdate
from yourtable
group by id
) t2
on t1.date = t2.maxdate and t1.id = t2.id;
谢谢戈登!这是有道理的,我相信你已经解决了我的问题!
select t1.id, t1.type, t1.date
from yourtable as t1 inner join
(select id, max(date) maxdate
from yourtable
group by id
) t2
on t1.date = t2.maxdate and t1.id = t2.id;