[英]How to sum a mathmatical result from two tables in MySQL
不知道该怎么办!
使用 MySQL
我需要显示特定 operatorID 的每小时总行程
因此,operatorid '2' 的总时数应该在某处显示为数字 '7'。 这个数字“7”是 TripsPerHour 的总和。
SELECT S.routeid, S.operatorid, R.routeid, S.percentage * R.frequency/100 AS TripsPerHour
FROM route_split S, routes R
WHERE R.routeid = S.routeid
AND S.operatorid ='2';
+---------+------------+---------+--------------+
| routeid | operatorid | routeid | TripsPerHour |
+---------+------------+---------+--------------+
| 6 | 2 | 6 | 1.0000 |
| 12 | 2 | 12 | 4.0000 |
| 13 | 2 | 13 | 2.0000 |
+---------+------------+---------+--------------+
3 rows in set (0.00 sec)
您只需要SUM()
聚合以及GROUP BY
子句
SELECT S.operatorid, R.routeid,
SUM(S.percentage * R.frequency/100) AS TripsPerHour
FROM route_split S
JOIN routes R
ON R.routeid = S.routeid
GROUP BY S.operatorid, R.routeid
如果您只需要operatorid=2
的值,则添加
WHERE S.operatorid = 2
在GROUP BY
之前,例如
SELECT R.routeid,
SUM(S.percentage * R.frequency/100) AS TripsPerHour
FROM route_split S
JOIN routes R
ON R.routeid = S.routeid
WHERE S.operatorid = 2
GROUP BY R.routeid
更新:您可以添加SUM() OVER ()
window function,前提是您的数据库版本为8.0+
,例如
SELECT S.operatorid, R.routeid,
SUM(S.percentage * R.frequency/100) OVER () AS Total_TripsPerHour
FROM route_split S
JOIN routes R
ON R.routeid = S.routeid
WHERE S.operatorid = 2
您还可以使用 WITH ROLLUP 选项将累积总和作为单独的行:
SELECT S.operatorid, R.routeid,
SUM(S.percentage * R.frequency/100) AS TripsPerHour ) FROM
route_split S JOIN routes R
ON R.routeid = S.routeid GROUP BY S.operatorid, R.routeid WITH ROLLUP
无论您选择哪个答案,在将其投入生产之前对其进行解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.