[英]How to sum a mathmatical result from two tables in MySQL
Not sure what to do!不知道该怎么办!
Using MySQL使用 MySQL
I need to display the total trips per hour a specific operatorID我需要显示特定 operatorID 的每小时总行程
So the total tripsperhour for operatorid '2' should be displayed as a number '7' somewhere.因此,operatorid '2' 的总时数应该在某处显示为数字 '7'。 This number '7' is the sum of TripsPerHour.这个数字“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)
You just need SUM()
aggregation along with GROUP BY
clause您只需要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
If you only need the value with operatorid=2
, then add如果您只需要operatorid=2
的值,则添加
WHERE S.operatorid = 2
before GROUP BY
such as在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
Update: you can add SUM() OVER ()
window function provided that your DB version is 8.0+
such as更新:您可以添加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
You could also use the WITH ROLLUP option to get your cumulative sum as a separate row:您还可以使用 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
Whichever answer you choose, do an EXPLAIN on it before you put it into production.无论您选择哪个答案,在将其投入生产之前对其进行解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.