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

高难度问题!查询进场时间及停留时间!
表结构

表格1:
(人员ID,区域,到达时间)
ryid,address,ddtime
1,       a区,2007-04-16   10:00:22
2,       a区,2007-04-16   10:02:22
1,       b区,2007-04-16   10:05:22
1,       c区,2007-04-16   10:00:22
表格2:
address   state
a区   进口
C区     出口

1).查询结果构成:
 ryid,最后所在的区域,进入时间,到达最后区域的时间,总停留时间,在最后区域停留时间.


------解决方案--------------------
第二个的方法:

select a.ryid,a.ddtime as '进入时间 ',b.ddtime as '出口时间 ',datediff(mi,a.ddtime,b.ddtime) as '停留时间(单位:分钟) ' from table1 a left join table1 b
on a.ryid=b.ryid
where a.address= 'a区 ' and b.address= 'c区 '
------解决方案--------------------
第一个问题:

select m.ryid,n.address as 最后所在的区域,m.ddtime as 进入时间,n.ddtime as 到达最后区域的时间,总停留时间,在最后区域停留时间
from
(
select *,总停留时间=datediff(mi,ddtime,(select top 1 ddtime from table1 c where a.ryid=c.ryid and a.ddtime <c.ddtime order by ddtime desc)) from table1 a where not exists(select 1 from table1 b where a.ryid=b.ryid and a.ddtime> b.ddtime) and address= 'a区 '
)m left join
(
select *,在最后区域停留时间=datediff(mi,ddtime,(select ddtime from table1 c where a.ryid=c.ryid and a.ddtime <c.ddtime)) from table1 a where not exists(select 1 from table1 b where a.ryid=b.ryid and a.ddtime <b.ddtime and b.address <> 'c区 ') and address <> 'a区 '
and address <> 'c区 '
)n on m.ryid=n.ryid