具有GROUP BY和JOIN的TIMEDIFF的AVG

时间:2019-08-24 00:40:00

标签: mysql sql

我需要总结一个使用两个表的KPI。基本上是两个表中日期字段之间的t1.ID,t2.ID和TIMESTAMPDIFF,如下所示(ps .:代码本身稍长-我仅在下面保留了要表示问题的基本内容):

SELECT `ticket`.`id` AS `Ticket`, `article`.`change_by` AS `UserID`,
TIMESTAMPDIFF(MINUTE, `ticket`.`create_time`, min(`article`.`create_time`)) AS `TimeDiff`
FROM `article`, `ticket`
WHERE `ticket`.`id` = `article`.`ticket_id`
GROUP BY `Ticket`, `UserID`

所以,结果是这样的:

Ticket           |UserID|TimeDiff
_________________________________
2019080141000014 |     7|       2
2019080141000023 |    11|       1
2019080141000032 |     7|       2
2019080141000041 |     7|       3
2019080141000051 |     7|      83
2019080141000069 |    11|       1

我正在寻找的结果是:

UserID|TimeDiff
_______________
     7|      90
    11|       2

我该怎么办?

编辑:让我头疼的是,每张票证create_time的计算是 ,而我想要的最终结果是 userID GROUP BY。

3 个答案:

答案 0 :(得分:0)

spctl -a -v /Applications/Pages.app 
/Applications/Pages.app: accepted
source=Mac App Store

答案 1 :(得分:0)

如果您希望每个用户一行,那应该是group by。聚合查询通常会具有聚合功能。

您的聚合遇到a.change_by问题。它既不聚合也不在GROUP BY中。

所以,我想你要

SELECT a.change_by AS UserID,
       SUM(TIMESTAMPDIFF(MINUTE, t.create_time, a.create_time)) AS TimeDiff
FROM article a JOIN
     ticket t
     ON t.id = a.ticket_id
WHERE a.create_time = (SELECT MIN(a2.create_time)
                       FROM article a2
                       WHERE a2.ticket_id = a.ticket_id
                      )
GROUP BY UserID;

其他四点:

  • 学习使用正确的,明确的,标准 JOIN语法。
  • 尴尬地使用反引号只会使查询难以阅读。
  • 表别名使查询更易于编写和阅读。
  • 在MySQL 8+中,您可以使用窗口函数更简洁地表达这一点。

答案 2 :(得分:-1)

首先,您要从Ticket语句中删除GROUP BY字段。

然后,您只需将选择内容包装在AVG()

SELECT `ticket`.`id` AS `Ticket`, `article`.`change_by` AS `UserID`,
TIMESTAMPDIFF(MINUTE, `ticket`.`create_time`, min(`article`.`create_time`)) AS `TimeDiff`,
AVG(TIMESTAMPDIFF(MINUTE, `ticket`.`create_time`, min(`article`.`create_time`))) AS `TimeDiff_AVG`
FROM `article`, `ticket`
WHERE `ticket`.`id` = `article`.`ticket_id`
GROUP BY `UserID`