我有两个具有相同列名的独立表,如下所示:
T1:
request_submit_time | request_complete_time
2017-04-12 13:20:23 | 2017-04-12 13:21:23
2017-04-12 13:15:54 | 2017-04-13 13:10:54
T2:
request_submit_time | request_complete_time
2017-04-13 13:21:23 | 2017-04-15 13:30:23
2017-04-14 13:15:54 | 2017-04-15 13:09:54
我知道如何使用以下方法从单个表中获取时间的平均值:
SELECT AVG(timestampdiff(HOUR,request_submit_time,request_complete_time)) AS average FROM tbl1;
但我无法弄清楚如何获得2个表中2列之间的平均时间。
答案 0 :(得分:1)
使用UNION ALL连接两个表中的结果集,然后计算:https://dev.mysql.com/doc/refman/5.7/en/union.html
SELECT AVG(timestampdiff(HOUR,request_submit_time,request_complete_time)) AS
average FROM
(
(SELECT request_submit_time, request_complete_time FROM tbl1)
UNION ALL
(SELECT request_submit_time, request_complete_time FROM tbl2)
)
修改 - mpen是正确的。您必须使用UNION ALL,因为UNION将删除重复项。谢谢你。