日期:2014-05-17  浏览次数:20419 次

急求SQL语句!!!
表:用户id,桌子id,登录状态,登录时间,退出时间

一张桌子上有可能有多个用户登录,每个用户的最后一条记录为当前登录状态记录。

找出某个时间段,该桌子上用户的最后一条登录状态记录,如果有用户在这个时间段没有记录,那么不查出来。




SQL MYSQL

------解决方案--------------------
1、测试数据
2、业务逻辑
3、想要的结果
------解决方案--------------------


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