2010-01-13 60 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