您好我想知道基于下表的作业执行时间。 例如,1/24/17,“运行”和“已完成”之间的时差为17分钟。
**JobName** **CurrentJobStatus** **TimeOfChange**
Customer Completed 1/24/17 0:17
Customer Running 1/24/17 0:00
Customer Waiting 1/23/17 20:30
Customer Completed 1/21/17 0:47
Customer Idle 1/21/17 16:00
Customer Running 1/21/17 0:30
Customer Completed 1/20/17 0:31
Customer Idle 1/20/17 16:00
Customer Running 1/20/17 0:15
Customer Waiting 1/20/17 20:30
Customer Completed 1/19/17 0:37
Customer Idle 1/19/17 16:00
Customer Running 1/19/17 0:20
Customer Waiting 1/19/17 20:30
答案 0 :(得分:1)
假设每天只有1 Running
和Completed
个工作状态,并且您想要两者之间的时差,您可以通过添加case
语句来使用条件聚合在max
或min
内:
select * , datediff(minute, completed, running)
from (
select
convert(date, TimeOfChange) change_date,
max(case when CurrentJobStatus = 'Completed' then TimeOfChange end) completed,
min(case when CurrentJobStatus = 'Running' then TimeOfChange end) running
from mytable
group by convert(date, TimeOfChange)
) t order by change_date
答案 1 :(得分:1)
我已选择使用CurrentJobStatus的行('已完成','正在运行'),然后我按TimeOfChange排序的CurrentJobStatus设置排名。这为每对('已完成','正在运行')
添加了序列号最后按此等级进行分组,获取最大和最小日期之间的约会。
with tm as
(
select JobName, CurrentJobStatus, TimeOfChange,
rank() over (partition by CurrentJobStatus order by TimeOfChange desc) rn
from jobs
where CurrentJobStatus in ('Completed', 'Running')
)
select
rn, DateDiff(minute, min(TimeOfChange), max(TimeOfChange)) as min
from tm
group by rn;
答案 2 :(得分:1)
这可能很棘手。如果我们假设“Running”和“Completed”完全交织在一起(没有两个“Running”后跟一个“Completed”),那么你可以通过计算每条记录之前或之前的“Running”记录的数量来识别匹配。其余的只是聚合:
select min(case when CurrentJobStatus = 'Running' then TimeOfChange end) as running_time,
max(case when CurrentJobStatus = 'Completed' then TimeOfChange end) as completed_time,
datediff(minute,
min(case when CurrentJobStatus = 'Running' then TimeOfChange end),
max(case when CurrentJobStatus = 'Completed' then TimeOfChange end)
) as diff_in_minutes
from (select t.*,
sum(case when CurrentJobStatus = 'Running' then 1 else 0 end) over (order by TimeOfChange) as running_running
from t
) t
group by running_running;
如果假设不成立,并且您可以连续多次“运行”或连续“完成”,那么您应该提出另一个问题,其中包含适当的样本数据和规则说明。