0

I have a temporary table whose structure is a below.

create table #temptime
(
   logtime datetime,
   [status] varchar(3)
)

As you can see from above , I have logintime and status. I need to partition this table based on status , ordered by date. I will need to calculate time span between these two created partition and consolidate to find how long user is in the premise.

For example let's say we have 4 records

Partition based on status IN        Partition based in status OUT

8:45 AM                                 10:45 AM
11:00 AM                                15:00 PM

Now program should find time span

10:45 AM - 8:45 AM = 2 Hours + 11:00 Am - 15:00 PM = 4 Hours

Whats the best way to accomplish this task?

Thanks

4

1 回答 1

3

尝试这个:

;with cte_IN as (select logtime,ROW_NUMBER() 
                       over (partition by [status] order by logtime) row_num
from #temptime
where [status]='IN'),
cte_OUT as (select logtime,ROW_NUMBER() 
                        over (partition by [status] order by logtime) row_num
from #temptime
where [status]='OUT')
select i.logtime,O.logtime,DATEDIFF(MI,i.logtime,O.logtime)/60.0 as 'hours'
from cte_IN I
join cte_OUT O
on I.row_num=O.row_num 


SQL 小提琴演示

于 2012-09-06T09:28:54.417 回答