34,593
社区成员
发帖
与我相关
我的任务
分享
SELECT a.* FROM tb a JOIN (
SELECT min(id) id,name1 FROM tb
GROUP BY name1
) b
ON a.id=b.id
ORDER BY a.id
declare @t table (id int,name1 varchar(1),name2 varchar(10),createTime varchar(6))
insert into @t
select 1,'a','2011-04-04','14:50' union all
select 2,'a','2011-04-04','14:52' union all
select 3,'a','2011-04-04','14:20' union all
select 4,'b','2011-04-04','11:12' union all
select 5,'b','2011-04-04','11:11' union all
select 6,'f','2011-04-03',null union all
select 7,'g','2011-04-02',null union all
select 8,'k','2011-04-01',null
select * from @t t where id=
(select min(id) from @t where name2=t.name2 and name1=t.name1)
order by id
/*
id name1 name2 createTime
----------- ----- ---------- ----------
1 a 2011-04-04 14:50
4 b 2011-04-04 11:12
6 f 2011-04-03 NULL
7 g 2011-04-02 NULL
8 k 2011-04-01 NULL
*/
Select * From # s Where Not Exists(Select 1 From # where s.name1=#.name1 and s.id>#.id)
--Exists子查询
--你要是想只取ID最小的记录就用这个,要是取时间就用CreateTime
select id,name,min(convert(datetime,createTime)) from table
group by id,name
order by id, name1, createTime desc
--sql2000的语法,不知道能不能用
select from tb a where id in (select top 1 id from tb b where a.name1=b.name1 order by b.id)
select * from tb t where id=(select min(id) from tb where name1=.name1 and createTime
=t.createTime)