2010-01-13 36 views
1

让说,我有表类似于下面select语句得到持续时间

actionTable 
----------- 
id, user, actionName, time 
1 , userX, startdoing, 1/1/2010 9am 
2, userX, endDoing,  2/1/2010 10am 

我可以知道是否可以从1使用1个SQL SELECT语句分钟记录2,并得到所花费的时间?或者使用hibernate.criteria来做到这一点?

回答

1

像这样几个小时

select s.[user], datediff(hh,s.time,e.time) as duration 
from actiontable s 
join actiontable e on s.[user] = e.[user] and e.actionname = 'enddoing' 
where s.actionname = 'startdoing' 

给我这个:

user  duration 
---------- ----------- 
userX  745 

更改为datediff(minute,s.time,e.time)给出了这样的

user  duration 
---------- ----------- 
userX  44700 

这会为用户的整个工作表中的开始和结束时间,如果你只有一个开始和结束时间每个...如果你不“T只有一个,然后就有点复杂 - 最简单的方式(与MSSQL 2005+)是做这样的事情是这样的:

;with sitems as 
(
    select [user], max([time]) as [time] 
    from actiontable 
    where actionname = 'startdoing' 
    group by [user] 
), eitems as 
(
    select [user], max([time]) as [time] 
    from actiontable 
    where actionname = 'enddoing' 
    group by [user] 
) 
select s.[user], datediff(minute,s.time,e.time) as duration 
from sitems s 
join eitems e on s.[user] = e.[user] 
+0

DATEDIFF在Oracle – cometta 2010-01-13 03:55:27

+0

使用SUBSTR工作 – cometta 2010-01-13 04:10:29

+0

不存在如果你是使用oracle然后最后一个(包含WITH)也不起作用。你必须使用临时表。 – Hogan 2010-01-13 04:38:05