0

我有两个查询 A & B 说,如下:

SELECT SUM(TIME_TO_SEC(TIMEDIFF(od.created_at, oc.created_at))) AS `sum (secs)`
FROM on_connected oc
JOIN on_disconnected od ON od.call_id = oc.call_id
WHERE oc.ext_num = 3205006;
+------------+
| sum (secs) |
+------------+
|    14      |
+------------+
1 row in set (0.00 sec)

SELECT count(TIME_TO_SEC(TIMEDIFF(od.created_at, oc.created_at))) AS `total calls`
FROM on_connected oc
JOIN on_disconnected od 
ON od.call_id = oc.call_id
WHERE oc.ext_num = 3205006;
+-----------------+
| total calls     |
+-----------------+
|               3 |
+-----------------+
1 row in set (0.00 sec)

我想将结果用于 MySQL 中的除法运算,如下所示:

SELECT A DIV B

这会给我一个 14/3 = 4 的结果。我尝试了什么?

SELECT
(SELECT SUM(TIME_TO_SEC(TIMEDIFF(od.created_at, oc.created_at))) AS `sum (secs)`
FROM on_connected oc
JOIN on_disconnected od ON od.call_id = oc.call_id) a

INNER JOIN

(SELECT count(TIME_TO_SEC(TIMEDIFF(od.created_at, oc.created_at))) AS `total calls`
FROM on_connected oc
JOIN on_disconnected od ON od.call_id = oc.call_id) b
WHERE oc.ext_num = 3205006;

INNER JOIN 语法妨碍了我的 DIV 运算符吗?

4

1 回答 1

0

这应该这样做。

SELECT
  SUM(TIME_TO_SEC(TIMEDIFF(od.created_at, oc.created_at))) /
  COUNT(*) AS `sec_per_call`
FROM on_connected oc
JOIN on_disconnected od ON od.call_id = oc.call_id
WHERE oc.ext_num = 3205006

您不需要两个子查询,因为两者的标准是相同的。您只需要划分两个聚合。

而且,count(TIME_TO_SEC(TIMEDIFF(od.created_at, oc.created_at)))真的没有意义。该函数只计算非空值,COUNT()无需在其中进行复杂的转换。如果你只是想知道调用次数,那只是匹配的行数,也就是.TIMEDIFFTIME_TO_SECCOUNT(*)

其实还可以进一步简化。SUM/COUNT 只是平均值,SQL 有一个内置AVG函数:

SELECT AVG(TIME_TO_SEC(TIMEDIFF(od.created_at, oc.created_at))) AS `sec_per_call`
FROM on_connected oc
JOIN on_disconnected od ON od.call_id = oc.call_id
WHERE oc.ext_num = 3205006
于 2013-09-02T14:50:21.237 回答