按ID分组并选择最近的

时间:2014-09-19 16:27:48

标签: sql ms-access group-by

我有一个像这样的表格示例:

 date        id     status
 01/01/2013  55555  high 
 01/01/2014  55555  low 
 01/01/2010  44444  high
 01/01/2011  33333  low

我需要按顺序:group by id并选择最近的日期。

这是我想要的结果。

 date        id     status
 01/01/2014  55555  low 
 01/01/2010  44444  high
 01/01/2011  33333  low

我不关心行的顺序。

3 个答案:

答案 0 :(得分:3)

您需要使用子查询加入您的表,该子查询将记录日期与每个ID的最大日期“链接”:

select a.*
from your_table as a
     inner join (
         select id, max(date) as max_date 
         from your_table 
         group by id
     ) as b on a.id = b.id and a.date = b.max_date;

答案 1 :(得分:2)

我认为您需要一个子查询来获取MAX(日期)然后才能获得内部联接。试试这个:

SELECT A.[Date], A.[Id], A.[Status]
FROM Table A
INNER JOIN(SELECT Id, MAX([Date]) AS MaxDate
FROM Table
GROUP BY [Id]) B ON
A.[Id] = B.[Id] AND
A.[Date] = B.[MaxDate]

答案 2 :(得分:0)

- 返回组ID和该组中的最新日期

select id
, MAX([date]) [latestDateInGroup]
from tbl 
group by id

- 返回组ID,以及该组中最新日期的记录的相关状态和日期

select id
, [status] [latestDateInGroup'sStatus]
, [date] [latestDateInGroup]
from
(
    select id
    , [status]
    , [date]
    , row_number() over (partition by id order by [date] desc) r
    from tbl
) x
where x.r = 1

- 返回所有ID和状态,以及该组的最新日期(需要SQL 2012 +)

select id
, [status]
, max([date]) over (partition by id order by [date] desc) [latestDateInGroup]
from tbl

SQL Fiddle目前处于离线状态;一旦备份,下面的代码应该允许你构建一个表来测试上面的查询 http://sqlfiddle.com

create table tbl ([date] date, id bigint, [status] nvarchar(4))
go

insert tbl select '2013-01-01', 55555, 'high'
insert tbl select '2014-01-01', 55555, 'low' 
insert tbl select '2010-01-01', 44444, 'high'
insert tbl select '2011-01-01', 33333, 'low'
相关问题