ID, LastUpdateTime , Field1
1 2001-01-01 a
2 2003-03-03 b
3 2004-04-04 b
4 1999-09-09 a
我希望通过SQL,得到如下结果: 即,按Field1 进行分组,取日期最大的一条记录的ID。
a 1 (Field1 = a 时,日期最大的一条记录,对应的ID 为 1 )
b 3 (Field1 = b 时,日期最大的一条记录,对应的ID 为 3 )
请高手指点。谢了!
...全文
2588打赏收藏
DB2:关于分组的SQL语句
表结构及数据如下如下: ID, LastUpdateTime , Field1 1 2001-01-01 a 2 2003-03-03 b 3 2004-04-04 b 4 1999-09-09 a 我希望通过SQL,得到如下结果: 即,按Field1 进行分组,取日期最大的一条记录的ID。 a 1 (Field1 = a 时,日期最大的一条记录,对应的ID 为 1 ) b 3 (Field1 = b 时,日期最大的一条记录,对应的ID 为 3 ) 请高手指点。谢了!
select ID, Field1 from table1 A, (
select Field1, max(LastUpdateTime) as LastUpdate from table1 group by Field1
) as B
where A.Field1 = B.Field1 and A.LastUpdateTime = B.LastUpdate
[Quote=引用 3 楼 wwwwb 的回复:]
可以
select a.* from tt a
inner join
(select Field1,max(LastUpdateTime) as ma from tt group by Field1) b
on a.Field1=b.Field1 and a.LastUpdateTime=b.ma
[/Quote]
or
select a.LastUpdateTime,a.Field1 from tt a left join tt b
on a.Field1=b.Field1 and a.LastUpdateTime<=b.LastUpdateTime
group by a.LastUpdateTime,a.Field1 having count(b.id)=1