日期:2014-05-17 浏览次数:20474 次
if object_id('Tempdb..#temp') is not null drop table #temp
--建临时表
create table #temp(
Id int identity(1,1) not null,
userid int null,
tableid int null,
loginstatus int null,
logintime datetime null,
quittime datetime null
)
--测试用例
Insert #temp
select 1,1,1,'2013-06-21 01:00:00','2013-06-21 05:00:00' union all
select 2,1,1,'2013-06-21 01:20:00','2013-06-21 01:25:00' union all
select 3,1,1,'2013-06-21 01:30:00','2013-06-21 01:40:00' union all
select 1,1,1,'2013-06-22 02:00:00','2013-06-22 02:30:00' union all
select 2,1,1,'2013-06-22 02:20:00','2013-06-22 02:45:00' union all
select 3,1,1,'2013-06-22 02:10:00','2013-06-22 03:20:00' union all
select 1,1,1,'2013-06-23 03:00:00','2013-06-23 03:10:00' union all
select 2,1,1,'2013-06-23 03:20:00','2013-06-23 04:55:00' union all
select 3,1,1,'2013-06-23 03:30:00','2013-06-23 03:40:00'
--定义 查询时间、桌子id 变量
declare @querytime datetime
declare @tableid int
set @querytime='2013-06-22 03:10:00'
set @tableid=1
--根据你的条件查询
--本例查询 桌子id为1 、时间为 2013-06-22 03:10:00 的登录记录
select * from #temp
where tableid=@tableid and (@querytime between logintime and quittime)
--查询结果
(9 行受影响)
Id userid tableid loginstatus logintime quittime
----------- ----------- ----------- ----------- ----------------------- -----------------------
6 3 1 1 2013-06-22 02:10:00.000 2013-06-22 03:20:00.000
select * from tablename t
where dtime=(select max(dtime) from tablename where userid=t.userid)
and dtime between 开始时间 and 结束时间
--时间段 starttime,endtime
--tableid 具体id你自己定
declare @tableid int