gpt4 book ai didi

mysql - 根据选择选择最后一个不同值和 TIMEDIFF?

转载 作者:行者123 更新时间:2023-11-29 22:17:05 26 4
gpt4 key购买 nike

我正在尝试设置一个查询,根据一列中最后一个唯一值出现的时间,在两次之间执行DATEDIFF。数据结构如下:

  row   ticket_id   create_time      change_time    owner_id     queue_id
1 11234 5/12/2014 13:47 5/12/2014 13:47 2 4
2 11234 5/12/2014 13:47 5/12/2014 13:47 2 4
3 11234 5/12/2014 13:47 5/12/2014 13:47 8 11
4 11234 5/12/2014 13:47 5/12/2014 13:47 8 11
5 11234 5/12/2014 14:02 5/12/2014 14:02 3 9
6 11234 5/12/2014 14:10 5/12/2014 14:10 17 5
7 11234 5/14/2014 12:00 5/14/2014 12:00 17 5
8 11234 5/15/2014 12:27 5/15/2014 12:27 17 5

基本上,我想在“change_time”列的第 6 行和第 8 行之间执行 datediff。我想在每个 Ticket_id 的owner_id 列或queue_id 列中选择最终的不同数字,并计算更改时间的差异。有没有办法使用 MySQL 进行设置?遗憾的是,使用 MAX() 函数不起作用,因为最高和第二高更改时间并不总是与最终队列 ID 或所有者 ID 相关联。我知道在 SAS 中可以使用 do 循环和 counter+1 的组合来执行类似的操作,但是使用 SQL 可以执行类似的操作吗?

最佳答案

使用 SQL Select only rows with Max Value on a Column 中的一种技术,使用子查询获取每个 ticket_id 的最后一个 owner_id 。将其与表连接起来,以获取此票证和所有者的第一次和最后一次更改时间。

SELECT t1.ticket_id, DATEDIFF(MAX(t1.change_time), MIN(t1.change_time)) AS diff
FROM YourTable AS t1
JOIN (SELECT a.ticket_id, a.owner_id AS last_owner
FROM YourTable AS a
JOIN (SELECT ticket_id, MAX(row) AS max_row
FROM YourTable
GROUP BY ticket_id) AS b
ON a.ticket_id = b.ticket_id AND a.owner_id = b.max_row) AS t2
ON t1.ticket_id = t2.ticket_id AND t1.owner_id = t2.last_owner
GROUP BY t1.ticket_id

DEMO

关于mysql - 根据选择选择最后一个不同值和 TIMEDIFF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31125509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com