对于sql 2008中的审计表,我需要计算每个订单在给定步骤中的时间(表示为新列)。
Old New Time Entered Order Number
NULL Step 1 4/30/12 10:43 1C2014A
Step 1 Step 2 5/2/12 10:17 1C2014A
Step 2 Step 3 5/2/12 10:28 1C2014A
Step 3 Step 4 5/2/12 11:14 1C2014A
Step 4 Step 5 5/2/12 11:19 1C2014A
Step 5 Step 9 5/3/12 11:23 1C2014A
NULL Step 1 5/18/12 15:49 1C2014B
Step 1 Step 2 5/21/12 9:21 1C2014B
Step 2 Step 3 5/21/12 9:34 1C2014B
Step 3 Step 4 5/21/12 10:08 1C2014B
Step 4 Step 5 5/21/12 10:09 1C2014B
Step 5 Step 6 5/21/12 16:27 1C2014B
Step 6 Step 9 5/21/12 18:07 1C2014B
NULL Step 1 6/12/12 10:28 1C2014C
Step 1 Step 2 6/13/12 8:36 1C2014C
Step 2 Step 3 6/13/12 9:05 1C2014C
Step 3 Step 4 6/13/12 10:28 1C2014C
Step 4 Step 6 6/13/12 10:50 1C2014C
Step 6 Step 8 6/13/12 12:14 1C2014C
Step 8 Step 4 6/13/12 15:13 1C2014C
Step 4 Step 5 6/13/12 15:23 1C2014C
Step 5 Step 8 6/13/12 15:30 1C2014C
Step 8 Step 9 6/18/12 14:04 1C2014C
输出可以简单如下:
Order Number Step Time in Step
1C2014A Step 1 6:09
答案 0 :(得分:2)
这就是我提出的:
select
a1.OrderNumber,
a1.New as Step,
datediff(second, a1.TimeEntered, isnull(a2.timeEntered,getdate()))
as [Time in Step (seconds)]
from AuditTrail a1
left join AuditTrail a2
on a1.New = a2.Old
and a1.OrderNumber = a2.OrderNumber
对于订单永远不会出现的步骤,时间计算到当前时刻(getdate()
)
以上查询可以多次显示一个步骤(例如:订单1C2014C
多次执行步骤4。)
要按顺序/步骤分组并显示每个此类对的总时间,请改用此SQL语句:
select
a1.OrderNumber,
a1.New as Step,
sum(datediff(second, a1.TimeEntered, isnull(a2.timeEntered,getdate())))
as [Total Time in Step (seconds)]
from AuditTrail a1
left join AuditTrail a2
on a1.New = a2.Old
and a1.OrderNumber = a2.OrderNumber
group by a1.OrderNumber, a1.New
order by a1.OrderNumber