日期:2014-05-18 浏览次数:20574 次
create table tb(ID int,UserID varchar(10),thedate varchar(10),thetime varchar(10)) insert into tb values(1 ,'AL000984', '1899-12-30', '10:41:00') insert into tb values(5 ,'AL000984', '1899-12-30', '10:42:00') insert into tb values(6 ,'AL000984', '1899-12-30', '10:46:00') insert into tb values(14 ,'AL000984', '1899-12-30', '10:57:00') insert into tb values(17 ,'BL000985', '1899-12-30', '11:06:00') insert into tb values(18 ,'BL000985', '1899-12-30', '11:14:00') insert into tb values(44 ,'BL000985', '1899-12-30', '11:24:00') insert into tb values(50 ,'BL000985', '1899-12-30', '11:36:00') insert into tb values(51 ,'BL000985', '1899-12-30', '11:46:00') go select t.id,t.UserID,t.thedate,t.thetime,[minute] = 0 from ( select px=(select count(1) from tb where UserID=a.UserID and cast(thedate + ' ' + thetime as datetime)<cast(a.thedate + ' ' + a.thetime as datetime))+1 , * from tb a ) t where px = 1 union all select n.id,n.UserID,n.thedate,n.thetime,[minute]=datediff(minute,cast(m.thedate + ' ' + m.thetime as datetime),cast(n.thedate + ' ' + n.thetime as datetime)) from ( select px=(select count(1) from tb where UserID=a.UserID and cast(thedate + ' ' + thetime as datetime)<cast(a.thedate + ' ' + a.thetime as datetime))+1 , * from tb a ) m, ( select px=(select count(1) from tb where UserID=a.UserID and cast(thedate + ' ' + thetime as datetime)<cast(a.thedate + ' ' + a.thetime as datetime))+1 , * from tb a ) n where m.UserID = n.UserID and m.px = n.px - 1 order by t.userid,t.thedate,t.thetime drop table tb /* id UserID thedate thetime minute ----------- ---------- ---------- ---------- ----------- 1 AL000984 1899-12-30 10:41:00 0 5 AL000984 1899-12-30 10:42:00 1 6 AL000984 1899-12-30 10:46:00 4 14 AL000984 1899-12-30 10:57:00 11 17 BL000985 1899-12-30 11:06:00 0 18 BL000985 1899-12-30 11:14:00 8 44 BL000985 1899-12-30 11:24:00 10 50 BL000985 1899-12-30 11:36:00 12 51 BL000985 1899-12-30 11:46:00 10 */
------解决方案--------------------
create table tb(ID int,UserID varchar(10),thedate datetime,thetimes int) insert into tb(id,UserID,thedate) values(1 ,'AL000984', '1899-12-30 10:41:00') insert into tb(id,UserID,thedate) values(5 ,'AL000984', '1899-12-30 10:42:00') insert into tb(id,UserID,thedate) values(6 ,'AL000984', '1899-12-30 10:46:00')(
------解决方案--------------------
declare @t table (ID int,UserID varchar(10),thedate varchar(10),thetime varchar(10))