SQL Server:从具有最大列值的记录中选择值

时间:2012-07-31 14:34:26

标签: sql-server-2008

我有一些包含3列的表:ObjectID, ChangedOn, NewValue

示例数据:

ObjectId                                NewValue            ChangedOn
50E37991-777C-4813-B436-C6082CCA6BE2    Closed              2012-07-13 15:14:35.000
50E37991-777C-4813-B436-C6082CCA6BE2    ActiveForSupport    2012-07-13 15:13:33.930
50E37991-777C-4813-B436-C6082CCA6BE2    Closed              2012-07-13 15:12:47.787
50E37991-777C-4813-B436-C6082CCA6BE2    ActiveForSupport    2012-07-13 15:11:28.540
50E37991-777C-4813-B436-C6082CCA6BE2    Closed              2012-07-13 14:52:10.797
D9001738-E089-43B3-8E80-6993601C4E70    Closed              2012-06-27 08:03:27.550

需要ObjectId的群组数据,并显示3列:ObjectId, NewValue,其中包含ChangedOn到群组的最大值,ChangedOn的最大值为当前群组

对于测试数据,我必须得到以下结果:

 ObjectId                              NewValue            ChangedOn
     50E37991-777C-4813-B436-C6082CCA6BE2      Closed           2012-07-13 15:14:35.000
     D9001738-E089-43B3-8E80-6993601C4E70      Closed           2012-06-27 08:03:27.550 

1 个答案:

答案 0 :(得分:0)

试试这个

CREATE TABLE test3(ObjectId uniqueidentifier,NewValue varchar(100),ChangedOn datetime)
INSERT INTO test3
VALUES('50E37991-777C-4813-B436-C6082CCA6BE2','Closed','2012-07-13 15:14:35.000'),
('50E37991-777C-4813-B436-C6082CCA6BE2','ActiveForSupport','2012-07-13 15:13:33.930'),
('50E37991-777C-4813-B436-C6082CCA6BE2','Closed','2012-07-13 15:12:47.787'),
('50E37991-777C-4813-B436-C6082CCA6BE2','ActiveForSupport','2012-07-13 15:11:28.540'),
('50E37991-777C-4813-B436-C6082CCA6BE2','Closed','2012-07-13 14:52:10.797'),
('D9001738-E089-43B3-8E80-6993601C4E70','Closed','2012-06-27 08:03:27.550')

select t1.ObjectId,t1.NewValue,t2.maxChangedOn  from test3 t1 inner join 
(select ObjectId,MAX(ChangedOn) maxChangedOn from test3
group by ObjectId) t2
on t1.ObjectId =t2.ObjectId and t1.ChangedOn =t2.maxChangedOn