2

我需要使用 SQL 实现一个非常复杂的函数,但我不知道从哪里开始。

--------------------------------------------------------
Entity | Source |Destination |  Time
--------------------------------------------------------
E1     |   -    |  T12       |2012-05-17 10:13:01.000
E2     |   -    |  T22       |2012-05-17 10:13:02.000
E1     |   T12  |  T22       |2012-05-17 10:13:03.000
E2     |   T22  |  T12       |2012-05-17 10:13:04.000
E1     |   T22  |  T12       |2012-05-17 10:13:05.000
E2     |   T12  |  T21       |2012-05-17 10:13:06.000
E1     |   T12  |  T13       |2012-05-17 10:13:07.000
E2     |   T21  |  T23       |2012-05-17 10:13:08.000

---------------------------------------------------
Src/Dest | Type
---------------------------------------------------
   T11   | T1
   T12   | T1  
   T13   | T1 
   T21   | T2       
   T22   |  T2
   T23   |  T2
-----------------------------------------------------

我需要计算这两种类型中每个实体所花费的总时间。

例如:

E1在T12用了2sec(13:01-13:03),在T22用了2sec(13:03-13:05),在T12用了2sec(13:05-13:07)。因此,在 T1 中花费的时间是 4 秒,在 T2 中花费的时间是 2 秒

E2在T22用了2sec(13:02-13:04),在T12用了2sec(13:04-13:06),在T21用了2sec(13:06-13:08)。因此,在 T1 中花费的时间是 2 秒,在 T2 中花费的时间是 4 秒。

注意:我不能做最大 - 最小时间;我需要继续积累时间,直到没有可用的记录。

在 SQL Server 2012 中执行此操作的最简单方法是什么?如果需要,我可以创建任何中间表。谢谢!

4

1 回答 1

2

我相信这会奏效:

SELECT Entity,Destination'Type',Time,SUM(TimeDiff) OVER (PARTITION BY Entity, Destination ORDER BY Time)'Running Total'
FROM (SELECT Entity, LEFT(SOURCE,2)'Source',LEFT(Destination,2)'Destination',Time, DATEDIFF(second,LAG([Time]) OVER (PARTITION BY Entity ORDER BY [Time]),[time])'TimeDiff'
        FROM  #test
     )sub
ORDER BY TIME 

或者,如果您只想要给定实体/类型组合的总时间:

SELECT Entity, Type, MAX(Running_Total)
FROM (SELECT Entity,Destination'Type',Time,SUM(TimeDiff) OVER (PARTITION BY Entity, Destination ORDER BY Time)'Running_Total'
      FROM (SELECT Entity, LEFT(SOURCE,2)'Source',LEFT(Destination,2)'Destination',Time, DATEDIFF(second,LAG([Time]) OVER (PARTITION BY Entity ORDER BY [Time]),[time])'TimeDiff'
              FROM  Table1
           )sub
      )sub
GROUP BY Entity, Type
ORDER BY Entity, Type

演示: SQL 小提琴

于 2013-07-15T23:19:02.540 回答