【问题标题】:Find max value and show corresponding value from different field in MS Access在 MS Access 中查找最大值并显示来自不同字段的相应值
【发布时间】: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


    【解决方案1】:

    您可以对相关子查询使用第一种方法:

    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;
    

    【讨论】:

    • 谢谢戈登!这是有道理的,我相信你已经解决了我的问题!
    猜你喜欢
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    相关资源
    最近更新 更多