MYSQL 使用 GROUP BY 到 SUM timediff 得到总打开时间

Posted

技术标签:

【中文标题】MYSQL 使用 GROUP BY 到 SUM timediff 得到总打开时间【英文标题】:MYSQL use GROUP BY to SUM timediff to get a total open time 【发布时间】:2021-12-30 06:38:55 【问题描述】:

我有多个表,我必须将它们连接在一起才能计算出票已打开多长时间,我正在使用以下查询(我知道很复杂!):

SELECT DISTINCT u_db.environments.name AS Env_name, TIMEDIFF(u_db.tickets.close_date, u_db.tickets.created_date) AS Total_open_time 
FROM u_db.tickets
INNER JOIN u_db.ticket_units
ON u_db.tickets.id = u_db.ticket_units.ticket_id
INNER JOIN u_db.units
ON u_db.ticket_units.unit_id = u_db.units.id
INNER JOIN u_db.locations
ON u_db.units.location_id = u_db.locations.id
INNER JOIN u_db.location_groups
ON u_db.locations.locations_group_id = u_db.location_groups.id
INNER JOIN u_db.environments
ON u_db.location_groups.environment = u_db.environments.id
WHERE u_db.tickets.created_date >= '2021-09-01 00:00:00'
AND u_db.tickets.created_date < '2021-10-01 00:00:00'
AND u_db.location_groups.id IN (50,17,46,45,48,49)
AND u_db.tickets.id IN (132357,132361,132372,132473);

注意:close_date 和 created_date 存储为 TIMESTAMP。

这会生成以下输出:

Env_name Total_open_time
GA       27:38:59
GA       01:43:51
GR       04:32:58
GR       49:39:19

但是,我想按 Env_name 分组并对每个组的 Total_open_times 求和,所以我想要的输出是:

Env_name Total_open_time
GA       29:22:50
GR       54:12:17

当我按 Env_name 分组时,我似乎无法得到总和的时间,任何关于如何实现这一点的建议将不胜感激!

【问题讨论】:

【参考方案1】:

猜你可以以秒为单位求和,然后将秒转换为时间

SELECT u_db.environments.name AS Env_name, SEC_TO_TIME(SUM(TIMESTAMPDIFF(SECOND, u_db.tickets.created_date, u_db.tickets.close_date))) AS Total_open_time 
FROM u_db.tickets
INNER JOIN u_db.ticket_units
ON u_db.tickets.id = u_db.ticket_units.ticket_id
INNER JOIN u_db.units
ON u_db.ticket_units.unit_id = u_db.units.id
INNER JOIN u_db.locations
ON u_db.units.location_id = u_db.locations.id
INNER JOIN u_db.location_groups
ON u_db.locations.locations_group_id = u_db.location_groups.id
INNER JOIN u_db.environments
ON u_db.location_groups.environment = u_db.environments.id
WHERE u_db.tickets.created_date >= '2021-09-01 00:00:00'
AND u_db.tickets.created_date < '2021-10-01 00:00:00'
AND u_db.location_groups.id IN (50,17,46,45,48,49)
AND u_db.tickets.id IN (132357,132361,132372,132473)
GROUP BY Env_name

【讨论】:

不知何故这给了我以下结果: GA 55:17:58 GR 63:18:13 不幸的是,这不是正确的答案,还有其他想法吗? @Ikthezeus 一定是其他原因,与SEC_TO_TIME & TIMESTAMPDIFF 无关,返回的结果与TIMEDIFF 相同,请参考dbfiddle.uk/… 进行演示

以上是关于MYSQL 使用 GROUP BY 到 SUM timediff 得到总打开时间的主要内容,如果未能解决你的问题,请参考以下文章

使用 MySQL 通过 JOIN 获取 GROUP BY 中的 SUM

MySQL 条件 SUM 使用 GROUP BY 和 DISTINCT

T-SQL-Sum over Partition by 与 group by 组合

使用 GROUP BY 时 MySQL SUM 不起作用

mysql_分组group by

使用 sum 和 group by 选项的 Mysql 查询运行速度非常慢