English 中文(简体)
计算每日活动总期间
原标题:Calculation of total duration of events for a day
  • 时间:2011-10-25 11:20:21
  •  标签:
  • tsql

我们有一个称为“活动”的表格,有Id(int)栏、活动(时间)、活动标准(时间)和活动(时间)。

所有活动均在一天开始和结束(即第二天不结束任何事件),但在特定日期发生的事件可能相互重叠(包括其中一个事件可以完全覆盖另一个事件)。

在特定日期可能发生任何事件。

我想用一天计算一下T-SQL至少有一次活动的总持续时间。 我可在某一日期选择这些事件,如果两个事件相互重叠,如果不发生,甚至伪造,甚至写了恢复真实性的职能。

然而,我很抱歉,如何把记录放在奶制品中,并通过我的职能加以管理,在我摆脱事件之前,适当增加时间。

Can you help?

Chris

最佳回答

为此:

--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
问题回答

暂无回答




相关问题
How to write this T-SQL WHERE condition?

I ve got two tables: TableA Col1 Col2 TableB Col3 Col4 I want to join them together: SELECT * from TableA join TableB ON (...) Now, in place of ... I need to write an expression ...

Customer and Order Sql Statement

TSQL query to select all records from Customer that has an Order and also select all records from customer that does not have an Order. The table Customer contains a primary key of CustomerID. The ...

Recommended way of querying multiple Versioned tables

Have a win 2003 box with MSSQL 2005 running on it. There is a database which is populated every morning with new/modified SalesOrder made the previous day. The database has several tables: SalesOrder, ...

update duplicate record

I have a table with the following fields Id Name IsPublic i need to write a sql query that updates IsPublic to false where name has a duplicate. Only one of the duplicates should have IsPublic = ...

Define variable to use with IN operator (T-SQL)

I have a Transact-SQL query that uses the IN operator. Something like this: select * from myTable where myColumn in (1,2,3,4) Is there a way to define a variable to hold the entire list "(1,2,3,4)"? ...

Selecting records during recursive stored procedure

I ve got a content management system that contains a hierarchical structure of categories, with sub-categories subject to different ordering options at each level. Currently, that s retrieved by a (...

热门标签