我对SQL很陌生,无法为我想要完成的任务找到合适的命令。
我们有一个票务系统,允许我们暂停机票。我正在尝试生成一个报告,该报告仅显示故障单处于非保持状态的时间。
我在MySQL工作台中运行查询。
以下是我收集实现目标所需信息的查询:
select ID, HD_TICKET_ID, TIMESTAMP,
case when DESCRIPTION LIKE '%opened" to "hold%' then 'hold' else 'active' end as state,
DESCRIPTION
from H
D_TICKET_CHANGE
where HD_TICKET_ID = 7715
order by TIMESTAMP
以下是我的结果:
ID HD_TICKET_ID TIMESTAMP state DESCRIPTION
25040 7715 "2014-08-06 16:39:29" active "Ticket Created
25042 7715 "2014-08-06 17:13:15" active "Changed ticket Status from ""New"" to ""Opened"".
25078 7715 "2014-08-07 10:38:28" hold "Changed ticket Status from ""Opened"" to ""Hold"".
25081 7715 "2014-08-07 10:54:55" active "Changed assest name"
25201 7715 "2014-08-11 08:24:56" active "Changed ticket Title. Changed ticket Status from ""Hold"" to ""Opened"".
25202 7715 "2014-08-11 08:25:08" hold "Changed ticket Status from ""Opened"" to ""Hold"".
25341 7715 "2014-08-13 10:56:00" active "Changed ticket Status from ""Hold"" to ""Opened"".
25373 7715 "2014-08-13 13:41:01" hold "Changed ticket Status from ""Opened"" to ""Hold"".
25551 7715 "2014-08-15 13:54:21" active "Added resolution text. Changed ticket Status from""Hold"" to ""Closed"".
此时我被困住了。我如何将时间从1添加到3,因为票证处于活动状态并且需要报告该时间,但是因为票证处于暂停状态而减去3到4,并根据活动继续此添加或减法到这些结果的结尾vs hold?
答案 0 :(得分:0)
您需要获取下一个时间戳值。然后你可以通过聚合做你想做的事。我喜欢在MySQL中使用相关子查询:
select ID, HD_TICKET_ID, TIMESTAMP,
(case when DESCRIPTION LIKE '%opened" to "hold%' then 'hold'
else 'active'
end) as state, DESCRIPTION,
(select tc2.timestamp
from HD_TICKET_CHANGE tc2
where tc2.timestamp > tc.timestamp
order by tc2.timestamp
limit 1
) as next_timestamp
from HD_TICKET_CHANGE tc
where HD_TICKET_ID = 7715
order by TIMESTAMP;
然后,您可以将结果添加为:
select sum((case when state = 'active' then 1 else -1 end) *
timestampdiff(second, next_timestamp, timestamp)
) as TimeInSeconds
from (select ID, HD_TICKET_ID, TIMESTAMP,
(case when DESCRIPTION LIKE '%opened" to "hold%' then 'hold'
else 'active'
end) as state, DESCRIPTION,
(select tc2.timestamp
from HD_TICKET_CHANGE tc2
where tc2.timestamp > tc.timestamp and tc2.HD_TICKET_ID = tc.HD_TICKET_ID
order by tc2.timestamp
limit 1
) as next_timestamp
from HD_TICKET_CHANGE tc
where HD_TICKET_ID = 7715
) t;
这忽略了最后的时间戳,因为没有" next"价值和你的问题没有说明在这种情况下该做什么。