简体   繁体   中英

How to sum a mathmatical result from two tables in MySQL

Not sure what to do!

Using MySQL

I need to display the total trips per hour a specific operatorID

So the total tripsperhour for operatorid '2' should be displayed as a number '7' somewhere. This number '7' is the sum of 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

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

WHERE S.operatorid = 2

before GROUP BY such as

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

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:

         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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM