sql先排序再去除重复的问题,在线等
数据库中有数据,如
怎么查询才能使查询只出stid为1001、1015两条数据,就是后面时间那条数据最小的那条
就是返回的话只返回1001 2013-10-10 1015 3013-10-19 这两条
在线等
[解决办法]
if OBJECT_ID('tb') is not null
drop table tb
go
create table tb
(
stid int,
nexttm datetime
)
insert into tb
select 1015,'2014-01-12 20:33:00.000' union all
select 1015,'2014-01-12 20:33:00.000' union all
select 1001,'2013-10-10 13:47:00.000' union all
select 1001,'2013-10-10 13:47:00.000' union all
select 1015,'2013-10-19 20:33:00.000' union all
select 1015,'2013-11-12 20:33:00.000' union all
select 1015,'2014-01-12 20:33:00.000'
select stid,
nexttm as rtdid
from
(
select *,
ROW_NUMBER() over(partition by stid
order by nexttm asc) as rownum
from tb
)t
where rownum = 1
/*
stidrtdid
10012013-10-10 13:47:00.000
10152013-10-19 20:33:00.000
*/