0

我有一些包含 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 已更改
     50E37991-777C-4813-B436-C6082CCA6BE2 2012-07-13 15:14:35.000 关闭
     D9001738-E089-43B3-8E80-6993601C4E70 关闭 2012-06-27 08:03:27.550
4

1 回答 1

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 
于 2012-07-31T16:11:17.713 回答