表结构:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tab_test]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[tab_test]
GO
CREATE TABLE [dbo].[tab_test] (
[id] [int] NOT NULL ,
[value] [int] NOT NULL ,
[time] [datetime] NOT NULL
) ON [PRIMARY]
GO
运行的Sql语句:
select t1.*,t2.value from (SELECT id,max(time) as time FROM tab_test group by id) as t1,tab_test as t2 where t1.id=t2.id and t1.time = t2.time
SELECT t1.id, t1.value, t1.time
FROM t AS t1 INNER JOIN [select id, max(time) as mintime from t group by id]. AS t2 ON (t1.time=t2.mintime) AND (t1.id=t2.id);