如何取每组最新的一条数据?
id name groupid lastdatetime
1 aaa 001 2007-03-06
2 bbb 001 2007-03-07
3 ccc 001 2007-03-05
4 ddd 002 2007-03-05
5 eee 002 2007-03-08
--------------------------------------------
想得到这样的结果
id name groupid lastdatetime
2 bbb 001 2007-03-07
5 eee 002 2007-03-08
------解决方案--------------------select t.* from 表 t where t.id=(select max(id) from 表 where name=t.name)
------解决方案--------------------select * from tb a
where not exists(select * from tb where groupid=a.groupid and lastdatetime> a.lastdatetime)
------解决方案--------------------select tb1.* from tb1,(select groupid,max(lastdatetime) from tb1) t where tb1.groupid=t.groupid and tb1.lastdatetime=t.lastdatetime;
------解决方案--------------------也寫下
Select *
From TableName A
Where lastdatetime = (Select Max(lastdatetime) From TableName Where name = A.name)
------解决方案--------------------不写了,顶
------解决方案--------------------if object_id( 'pubs..tb ') is not null
drop table tb
go
create table tb
(
id int,
name varchar(10),
groupid varchar(10),
lastdatetime datetime
)
insert into tb(id,name,groupid,lastdatetime) values(1, 'aaa ', '001 ', '2007-03-06 ')
insert into tb(id,name,groupid,lastdatetime) values(2, 'bbb ', '001 ', '2007-03-07 ')
insert into tb(id,name,groupid,lastdatetime) values(3, 'ccc ', '001 ', '2007-03-05 ')
insert into tb(id,name,groupid,lastdatetime) values(4, 'ddd ', '002 ', '2007-03-05 ')
insert into tb(id,name,groupid,lastdatetime) values(5, 'eee ', '002 ', '2007-03-08 ')