为此:
--test table
declare @t table(fromt datetime, tot datetime)
--test data
insert @t values( 2011-01-01 10:00 , 2011-01-01 11:00 )
insert @t values( 2011-01-01 10:00 , 2011-01-01 10:05 )
insert @t values( 2011-01-01 10:30 , 2011-01-01 11:30 )
insert @t values( 2011-01-01 12:00 , 2011-01-01 12:30 )
insert @t values( 2011-01-02 12:00 , 2011-01-02 12:30 )
--query
;with f as
(
select distinct fromt from @t t
where not exists(select 1 from @t where t.fromt > fromt and t.fromt < tot)
), t as
(
select distinct tot from @t t
where not exists(select 1 from @t where t.tot >= fromt and t.tot < tot)
), s as
(
select datediff(day, 0, fromt) d, datediff(second, fromt, (select min(tot)
from t where f.fromt < tot and datediff(day, f.fromt, tot) = 0)) sec
from f
)
select dateadd(day, 0, d) day, sum(sec)/60 [minutes]
from s
group by d
order by d
结果:
day minutes
----------------------- -------
2011-01-01 00:00:00.000 120
2011-01-02 00:00:00.000 30