views:

35

answers:

1

let say i have table look like below

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

may i know whether possible to use 1 sql select statement to minute record 2 from 1 and get time spent ? or use hibernate.criteria to do this?

+1  A: 

something like this for hours

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' 

give me this:

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

changing to datediff(minute,s.time,e.time) gives this

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

this will work for an entire table of users and their start and end times if you only have one start and end time for each... if you don't have only one then it gets a little more complicated -- the easy way (with mssql 2005+) is to do something like like this:

;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] 
Hogan
datediff not exist in oracle
cometta
use SUBSTR work
cometta
If you are using oracle then the last one (containing WITH) will also not work. You have to use a temporary table.
Hogan