TSQL问题,用于计算一个表中两个日期之间的差异

时间:2011-08-01 12:18:26

标签: sql tsql sql-server-2008

在MSSQL 2008中,我有表格和数据,看起来像这样

create table #tempData
(user_id int,type varchar(10),ts datetime)

insert into #tempData
select 1,'ENTER','2011-01-30 15:00:00'
union all
select 1,'EXIT','2011-01-31 16:00:00'
union all
select 1,'ENTER','2011-02-1 18:00:00'
union all
select 1,'EXIT','2011-02-10 21:00:00'
union all
select 2,'ENTER','2011-01-10 21:00:00'
union all
select 2,'EXIT','2011-01-12 21:00:00'
union all
select 2,'ENTER','2011-01-13 01:00:00'
union all
select 2,'EXIT','2011-01-13 18:00:00'
--AND SO ON --

现在我尝试进行查询,根据最后一个出口确定一个用户在里面的时间

之类的东西
user_id,exited,time_in_hours
1,'2011-01-31 16:00:00',25 
1,'2011-02-10 21:00:00',219
2,'2011-01-12 21:00:00',48
2,'2011-01-13 18:00:00',17

对不起,如果这个BAD或ROUGE问题,如果这不是正确的方式来提出这样的问题。 但是我暂时不知所措。

4 个答案:

答案 0 :(得分:1)

假设

  • 相同用户会话不相交,

  • 如果没有相应的ENTER记录,则不能有EXIT记录,

你可以尝试以下方法:

WITH ranked AS (
  SELECT
    user_id,
    type,
    ts,
    rn = ROW_NUMBER() OVER (PARTITION BY user_id, type ORDER BY ts)
  FROM #tempData
)
SELECT
  tx.user_id,
  exited = tx.ts,
  hours = DATEDIFF(HOUR, tn.ts, tx.ts)
FROM ranked tn
  INNER JOIN ranked tx ON tn.user_id = tx.user_id AND tn.rn = tx.rn
WHERE tn.type = 'ENTER'
  AND tx.type = 'EXIT'

答案 1 :(得分:1)

使用CTE可以做到

with
  exits as ( select [user_id],ts from #tempData where type='EXIT'),
  entries as ( select [user_id],ts from #tempData where type='ENTER'),
  result as (
select 
RANK() over (Partition by a.user_id,b.ts order by a.ts desc) as i,
a.[user_id],b.ts as 'Last Exited',DATEDIFF(hh,a.ts,b.ts) as [hours]
from
    entries a inner join exits b on b.[User_id]=a.[User_id] and a.ts<b.ts
  )

select user_id,[Last Exited],hours from result where i=1

然而,该解决方案假设总是有一个退出记录,而该记录总是与前面的条目记录匹配

答案 2 :(得分:1)

尝试

select a.usr,a.ts enter_date
,min(b.ts) exit_date, datediff(ss,a.ts,min(b.ts)) diff_in_sec
from tempData a
    join tempdata b on a.usr = b.usr and a.ts < b.ts
where a.type='enter' and b.type='exit'
group by a.usr,a.ts

答案 3 :(得分:0)

试试这个:

SELECT user_id, exitTable.ts AS exited, DATEDIFF(hour, exitTable.ts, enterTable.ts) AS time_in_hours
FROM yourTable enterTable
    INNER JOIN yourTable exitTable
        ON enterTable.user_id = exitTable.user_id
            and exitTable.ts > enterTable.ts
                    and exitTable.type = 'EXIT'
WHERE enterTable.type = 'ENTER'
    and entertable.ts = (SELECT MAX(ts) FROM yourTable WHERE yourTable.user_id = enterTable.user_id AND type = 'ENTER')

一句解释......

WHERE子句将行限制为每个user_id的最后一个ENTER。 JOIN子句将该行与入口后有一段时间的EXIT连接起来。