我需要使用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中花费2秒(13:01-13:03),在T22中花费2秒(13:03-13:05),在T12中花费2秒(13:05-13:07)。因此,在T1中花费的时间是4秒,在T2中花费的时间是2秒
E2在T22中花费2秒(13:02-13:04),在T12中花费2秒(13:04-13:06),在T21中花费2秒(13:06-13:08)。因此,在T1中花费的时间是2秒,在T2中花费的时间是4秒。
注意:我不能做到最大 - 最短时间;我需要继续累积时间,直到没有可用的记录。
在SQL Server 2012中执行此操作的最简单方法是什么?如果需要,我可以创建任何中间表。谢谢!
答案 0 :(得分: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 Fiddle