我正在使用票务系统,并且需要编写一个查询来检查代理商是否在交付时迟到了。
这就是我现在所拥有的以及我需要的东西:
ticket_id time_created
例如:
ticket_id time_created
1 2013-08-19 12:11
1 2013-08-17 12:07
1 2013-08-17 12:00
2 2013-08-19 12:11
2 2013-08-19 12:10
结果
ticket_id time_difference
1 48:04
我只需要检查具有相同ticket_id号码的票证。
EDIT 让我们说也有和id列 我需要1,2和2,3之间的检查值(在这种情况下 - 所有ticket_id = 1) 和4,5(ticket_id = 2)
答案 0 :(得分:0)
像这样的东西可以解决这个问题:
select ticket_id, min(a.time_created), max(b.time_created),
TIMESTAMPDIFF(HOUR,min(a.time_created), max(b.time_created))
from tbl AS a JOIN tbl AS b USING(ticket_id)
where a.time_created < (b.time_created - INTERVAL 1 DAY)
group by(a.ticket_id);
产:
+------------+--------------------------------+--------------------------------+--------------------------------------------------------------+
| TICKET_ID | MIN(A.TIME_CREATED) | MAX(B.TIME_CREATED) | TIMESTAMPDIFF(HOUR,MIN(A.TIME_CREATED), MAX(B.TIME_CREATED)) |
+------------+--------------------------------+--------------------------------+--------------------------------------------------------------+
| 1 | August, 17 2013 12:00:00+0000 | August, 19 2013 12:11:00+0000 | 48 |
+------------+--------------------------------+--------------------------------+--------------------------------------------------------------+
请参阅http://sqlfiddle.com/#!2/4af76e/7
请注意,我在此处使用了TIMESTAMPDIFF
,请求HOUR
中的结果。由于TIMEDIFF
值的范围有限(≈34天),我在此处未使用TIME
。
答案 1 :(得分:0)
为了获得差异,您需要相当于MySQL不支持的lag()
函数。您可以使用相关子查询获得相同的效果:
select ticket_id, timediff(nextTimeCreated, time_created)
from (select t.*,
(select time_created
from t t2
where t2.ticket_id = t.ticket_id and
t2.time_created > t.time_created
) as nextTimeCreated
from t
) t
where nextTimeCreated > time_created + interval 1 day;
答案 2 :(得分:0)
此查询会检查上次日期和最低日期之间的差异,您希望这个或最后一个日期和第二个日期之间的差异
SELECT ticket_id,
DATEDIFF(MAX(TIME_CREATED),MIN(TIME_CREATED)) AS DiffDate
FROM TABLE1
group by ticket_id
此查询应查找两张最新票证之间的差异
SELECT ticket_id, TIMEDIFF(MAX(A.TIME_CREATED),
(SELECT MAX(TIME_CREATED) FROM TICKETS B
where B.TIME_CREATED <MAX(A.TIME_CREATED))) AS DiffDate
FROM TICKETS A
group by ticket_id
想想看,我现在认为这可能是
的重复Difference between dates in two consecutive rows
你可以在那里试试......
SELECT ticketid,extract(来自tdiff的epoch)FROM( 选择 ticketid, ticketdate - lag(ticketdate)OVER(按照ticketid ORDER BY ticketdate)AS tdiff, dense_rank()OVER(PARTITION BY ticketid ORDER BY ticketdate)AS等级 从表1 按顺序排列)x 等级= 2;
并在
处小提琴