Find max value and show corresponding value from different field in MS Access

别等时光非礼了梦想. 提交于 2019-12-10 12:04:21

问题


So I found this similar question and answer at (Find max value and show corresponding value from different field in SQL server) but I want to take it one step further. I want to get the latest date for each ID and the corresponding TYPE instead of just the absolute max for all entries. Any suggestions?

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 

The code below shows how to get just the max date of ALL entries, but I want the max date for each ID and then the corresponding Type.

select id, type, date
from yourtable
where date in (select max(date)
                     from yourtable)

OR

select id, type, date
from yourtable t1
inner join
(
  select max(date) maxdate
  from yourtable
) t2
  on t1.date = t2.maxdate;

回答1:


You can use the first method with a correlated subquery:

select id, type, date
from yourtable as t
where date in (select max(date)
               from yourtable as t2
               where t2.id = t.id);

Or, group by id in the second:

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;


来源:https://stackoverflow.com/questions/32203334/find-max-value-and-show-corresponding-value-from-different-field-in-ms-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!