1

我在 SQL 表中有以下信息(确实有其他相关字段,但这些是必需的主要数据)

Name        State       Time
tst1        Start       2012-06-24 11:51:48.5210000
tst1        Completed   2012-06-24 11:56:48.5210000
tst1        InProgress  2012-06-24 11:53:48.5210000
tst1        Completed   2012-06-24 11:56:48.5210000
tst1        InProgess   2012-06-24 11:53:48.5210000
tst1        Start       2012-06-24 11:51:48.5210000

上述数据用于测试,并带有相对状态的时间戳。我需要从获取开始时间戳和完成时间戳的差异来计算完成一项测试所需的时间。

以下格式是可选的。但是需要计算一个测试用例所花费的时间。如果我们有一个名称和时间戳相同的测试用例,则可以将其视为一个。

//可选格式
还需要获取一种状态到另一种状态的时间。

喜欢

Name    State                 Timetaken
tst1    start-Completed         5:00
tst1    start-Inprogress        2:00
tst1    Inprogress-Completed    3:00

注意:tst1数据记录的数据可以是随机的(如上表中状态是start,然后完成然后Inprogress)

4

2 回答 2

1

如果您有相同名称的测试的重叠时间,就像在示例中一样(两次在 11:51 开始,两次在 11:56 完成),则无法知道哪个完成对应于哪个开始。

SELECT t1.Name
    , CASE WHEN t1.State='Start' THEN 'Start-Inprogress'
           WHEN t1.State='InProgress' THEN 'Inprogress-Completed'
           WHEN t1.State='Completed' THEN 'Start-Completed'
    END AS State
    , CASE WHEN t1.State='Completed'
           THEN right(CONVERT(VARCHAR,(t1.Time-(SELECT max(Time) FROM TableName t2 WHERE t1.Name = t2.Name AND t2.Time < t1.Time AND t2.State='Start')),108),5)
           ELSE right(CONVERT(VARCHAR,((SELECT min(Time) FROM TableName t2 WHERE t1.Name = t2.Name AND t2.Time > t1.time AND t2.State!='Start')-t1.Time),108),5)
    END AS Timetaken
FROM TableName t1
GROUP BY t1.Name, t1.State, t1.Time
于 2013-06-26T10:32:52.223 回答
0

您可以将选项与 APPLY 运算符和值一起用作表源

SELECT [state], 
       CAST(COALESCE(Timetaken, Timetaken2, Timetaken3) AS time) AS Timetaken
FROM (
      VALUES('Start-Completed'),
            ('Start-Inprogress'),
            ('Inprogress-Completed')
      ) x([state]) 
CROSS APPLY (
             SELECT TOP 1 
               MAX(CASE WHEN [state] = 'Completed' 
                        THEN CAST([time] AS datetime) END) 
                 - MAX(CASE WHEN [state] = 'Start' 
                            THEN CAST([time] AS datetime) END) AS Timetaken,
               MAX(CASE WHEN [state] = 'InProgress' 
                        THEN CAST([time] AS datetime) END)
                 - MAX(CASE WHEN [state] = 'Start' 
                            THEN CAST([time] AS datetime) END) AS Timetaken2, 
               MAX(CASE WHEN [state] = 'Completed' 
                        THEN CAST([time] AS datetime) END) 
                 - MAX(CASE WHEN [state] = 'InProgress' 
                            THEN CAST([time] AS datetime) END) AS Timetaken3
             FROM dbo.test133 t
             WHERE x.[state] LIKE '%' + t.[state] + '%'
             GROUP BY name
             ) o

结果:

state                  Timetaken
Start-Completed        00:05:00.0000000
Start-Inprogress       00:02:00.0000000
Inprogress-Completed   00:03:00.0000000

请参阅SQLFiddle上的演示

于 2013-06-26T15:43:45.610 回答