好的,这是我的情况。我们以前的数据库专家(SQL Server 2008)设置了一个表来存储时间以用于性能目的。时间从VB脚本生成并输入到表中。
表演过程(表格中:从下到上):
e.g。
Msrmnt | Time | Window | Function | Position
--------+-------------------------+------------+----------+-----------
109 | 2016-05-10 20:35:32.243 | WindowName | Select | 2
109 | 2016-05-10 20:35:29.230 | WindowName | Select | 1
109 | 2016-05-10 20:35:26.697 | WindowName | Open | 2
109 | 2016-05-10 20:35:23.297 | WindowName | Open | 1
现在,我需要计算2个开放值(1& 2)之间的时间(例如)。我确实对DB有很多经验,但我仍然坚持我应该如何最好地接近这一点以确保我是1.)获得准确的结果,2。)计算在时间上是有效的(因为有一周内很多参赛作品)
感谢您的任何建议
卡伦
答案 0 :(得分:2)
如何获得两个时间值之间的计算时间的基本示例:
;WITH cte AS (
SELECT *
FROM (VALUES
(109, '2016-05-10 20:35:32.243', 'WindowName', 'Select', 2),
(109, '2016-05-10 20:35:29.230', 'WindowName', 'Select', 1),
(109, '2016-05-10 20:35:26.697', 'WindowName', 'Open', 2),
(109, '2016-05-10 20:35:23.297', 'WindowName', 'Open', 1)
) as t (Msrmnt, [Time], Window, [Function], Position)
)
SELECT c.Msrmnt,
c.Window,
DATEDIFF(MILLISECOND,c.[Time],c1.[Time]) as ms
FROM cte c
INNER JOIN cte c1
ON c.Msrmnt = c1.Msrmnt
AND c.Window = c1.Window
AND c.[Function] = c1.[Function]
AND c.Position + 1= c1.Position
WHERE c.[Function] = 'Open'
输出:
Msrmnt Window ms
----------- ---------- -----------
109 WindowName 3400
答案 1 :(得分:2)
基于SQL 2008中的日期顺序。如果平台是SQL 2012,那么这可以是LEAD或LAG功能。
;WITH X AS (
SELECT 109 AS Msrmnt, CAST('2016-05-10 20:35:32.243' AS DATETIME) As Date, 'WindowName' AS Window, 'Select' AS [Function], 2 AS Position UNION ALL
SELECT 109,CAST('2016-05-10 20:35:29.230' AS DATETIME),'WindowName' , 'Select',1 UNION ALL
SELECT 109,CAST('2016-05-10 20:35:26.697' AS DATETIME),'WindowName','Open',2 UNION ALL
SELECT 109,CAST('2016-05-10 20:35:23.297' AS DATETIME),'WindowName','Open',1
)
SELECT
DATEDIFF(S,x1.Date, x2.Date)
,x1.Date, x2.Date
FROM x as x1
INNER JOIN x as x2
ON x1.Msrmnt = x2.Msrmnt AND x1.Window = x2.Window AND x1.Date < x2.Date
WHERE x1.[Function] = 'Open' AND x2.[Function] = 'Open'