【发布时间】:2015-11-19 02:50:11
【问题描述】:
所以我在 (Find max value and show corresponding value from different field in SQL server) 找到了类似的问题和答案,但我想更进一步。我想获取每个 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 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 t1
inner join
(
select max(date) maxdate
from yourtable
) t2
on t1.date = t2.maxdate;
【问题讨论】:
标签: sql ms-access max greatest-n-per-group corresponding-records