日期:2014-05-18  浏览次数:20464 次

求最小时间/次小时间
表格如下:
id   time  
01     9:01
01     9:05
01     9:10
01     9:55
01     10:01
..     ...
02     9:11
02     9:55
02     10:01
02     10:11
..     ...

求特定ID大于某一时间的最小时间/次小时间
比如:   01的9:10
结果:   id   min     sec_min
            01   9:55   10:01

------解决方案--------------------
create table tb(id varchar(10) , time varchar(10))

insert into tb values( '01 ', '09:01 ')
insert into tb values( '01 ', '09:05 ')
insert into tb values( '01 ', '09:10 ')
insert into tb values( '01 ', '09:55 ')
insert into tb values( '01 ', '10:01 ')
insert into tb values( '02 ', '09:11 ')
insert into tb values( '02 ', '09:55 ')
insert into tb values( '02 ', '10:01 ')
insert into tb values( '02 ', '10:11 ')
go

declare @id as varchar(10)
set @id = '01 '
declare @dt as varchar(10)
set @dt = '09:10 '

SELECT * , [order]=(SELECT COUNT(time) FROM (select * from tb where id = @id and time > @dt) t WHERE time < a.time) + 1
FROM (select * from tb where id = @id and time > @dt) a
ORDER BY [order]

drop table tb

/*
id time order
---------- ---------- -----------
01 09:55 1
01 10:01 2

(所影响的行数为 2 行)
*/