我有以下格式化的表数据值。我想让最后一个操作完成状态开始时间和结束时间持续时间需要在下一个准备好的操作中显示。
例如:原始表格格式:
Sno Operation Status StartTime EndTime
------ ----------- ----------------- --------------------- ---------------
1 OP10 Complete 2017-03-01 07:00:00 2017-03-01 07:10:00
1 OP20 Complete 2017-03-01 07:10:00 2017-03-01 07:30:00
1 OP30 Ready Null Null
2 OP10 Complete 2017-03-01 08:00:00 2017-03-01 08:10:00
2 OP20 Ready Null Null
3 OP10 Complete 2017-03-01 09:00:00 2017-03-01 09:10:00
3 OP20 Complete 2017-03-01 10:00:00 2017-03-01 10:10:00
3 OP30 Ready 2017-03-01 10:00:00 2017-03-01 10:10:00
我需要这样的输出:
Sno Operation Status TotalDurationCountInMins
------ ------------ ------------ ---------------------------------
1 OP30 Ready 20
2 OP20 Ready 10
3 OP30 Ready 10
答案 0 :(得分:0)
使用子查询来完成最后一次操作。
注意:如果您的“操作”列包含无法排序的数据(例如“开始”,“中间”,“结束”),则此查询将生成错误结果
创建并填充样本表(请在将来的问题中保存此步骤)
DECLARE @T AS TABLE
(
Sno int,
Operation char(5),
[Status] varchar(8),
StartTime datetime,
EndTime datetime
)
INSERT INTO @T VALUES
(1, 'OP10', 'Complete', '2017-03-01 07:00:00', '2017-03-01 07:10:00'),
(1, 'OP20', 'Complete', '2017-03-01 07:10:00', '2017-03-01 07:30:00'),
(1, 'OP30', 'Ready', Null, Null),
(2, 'OP10', 'Complete', '2017-03-01 08:00:00', '2017-03-01 08:10:00'),
(2, 'OP20', 'Ready', Null, Null),
(3, 'OP10', 'Complete', '2017-03-01 09:00:00', '2017-03-01 09:10:00'),
(3, 'OP20', 'Complete', '2017-03-01 10:00:00', '2017-03-01 10:10:00'),
(3, 'OP30', 'Ready', '2017-03-01 10:00:00', '2017-03-01 10:10:00')
查询:
SELECT Sno,
Operation,
[Status],
(SELECT TOP 1 DATEDIFF(MINUTE, StartTime, EndTime)
FROM @T t2
WHERE t2.Sno = t1.Sno
AND t2.Operation < t1.Operation
AND t2.[Status] = 'Complete'
ORDER BY StartTime DESC
) AS TotalDurationCountInMins
FROM @T t1
WHERE [Status] = 'Ready'
结果:
Sno Operation Status TotalDurationCountInMins
1 OP30 Ready 20
2 OP20 Ready 10
3 OP30 Ready 10