我有下表(事务表),我正在使用MS SQL:
现在我需要做的是每位持卡人在同一行显示条目和匹配的退出。这样他们就可以看到这个人在建筑物内的时间。
我一直试图以各种方式解决这个问题,但我无法获得这些信息。任何有关如何处理此问题的建议将不胜感激。我一直在研究CTE方法,但我的问题是我很难让它工作。
答案 0 :(得分:0)
这说明了如何在Oracle中完成它。 trans
with子句当然是现实场景中的真实表格。要使此SQL在其他RDBMS中工作,您可能必须删除所有from dual
并更改时间字符串的解析和计算方式,以获得每次访问的秒数。 (Oracle中两个DATE
日期类型值的减法会为它们之间的天数留下一个浮点数,因此* 24 * 3600得到秒数。
with
trans as (
select 4 id, 'CT1' name, 54 tmhisid, 'Entry' caption, '2017-10-16 14:31:06' dt from dual union
select 5 id, 'CT2' name, 55 tmhisid, 'Entry' caption, '2017-10-16 14:31:14' dt from dual union
select 4 id, 'CT1' name, 56 tmhisid, 'Exit' caption, '2017-10-16 14:47:00' dt from dual union
select 5 id, 'CT2' name, 57 tmhisid, 'Exit' caption, '2017-10-16 14:47:05' dt from dual union
select 4 id, 'CT1' name, 58 tmhisid, 'Entry' caption, '2017-10-16 15:05:24' dt from dual union
select 5 id, 'CT2' name, 59 tmhisid, 'Entry' caption, '2017-10-16 15:05:33' dt from dual union
select 4 id, 'CT1' name, 60 tmhisid, 'Exit' caption, '2017-10-16 15:10:25' dt from dual union
select 5 id, 'CT2' name, 61 tmhisid, 'Exit' caption, '2017-10-16 15:10:29' dt from dual
),
trans2 as ( select trans.*, to_date(dt,'YYYY-MM-DD HH24:MI:SS') d from trans ),
entry as ( select * from trans2 where caption='Entry' ),
exit as ( select * from trans2 where caption='Exit' ),
visit as (
select en.id, en.name, en.d entry, ex.d exit
from entry en
join exit ex on ex.id=en.id
where ex.d>=en.d
and not exists (select 1 from exit ex2 where id=en.id and ex2.d>en.d and ex2.d<ex.d)
)
select visit.*, (exit-entry)*24*3600 sec from visit
order by entry;
结果:
ID NAM ENTRY EXIT SECONDS
---- --- ------------------- ------------------- --------
4 CT1 2017-10-16 14:31:06 2017-10-16 14:47:00 954
5 CT2 2017-10-16 14:31:14 2017-10-16 14:47:05 951
4 CT1 2017-10-16 15:05:24 2017-10-16 15:10:25 301
5 CT2 2017-10-16 15:05:33 2017-10-16 15:10:29 296