Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query - how to construct multiple SUMs (based on different parameters) in one query

Tags:

sql

mysql

Please review my tables below... Is it possible to build a single query capable of

1) calculating the SUM of total_time for all vehicles that have class_id 1 (regardless of feature_id)
(result would be 6:35)
2) calculating the SUM of total_time for all vehicles that have class_id 1 AND have feature_id 2
(result would be 5:35 based on vehicle_id 22 and 24)

I'm able to get the results in two seperate queries, but I was hoping to retrieve them in one single query.... something like:

SELECT 
    SUM((CASE WHEN (VEHICLE_TABLE.class_id = 1) then LOG_TABLE.total_time else 0 end)) **AS TOTAL_ALL**,
    ...here goes statement for 2)... AS TOTAL_DIESEL...
FROM LOG_TABLE, VEHICLE_TABLE .....
WHERE VEHICLE_TABLE.vehicle_id = LOG_TABLE.vehicle_id ......


TABLE 1: LOG_TABLE (vehicle_id is NOT unique)
vehicle_id  |  total_time
--------------|--------------
      22               2:00
      22               0:30
      23               1:00
      24               2:20
      24               0:45

TABLE 2: VEHICLE_TABLE (vehicle_id is unique)
vehicle_id  |  class_id
--------------|--------------
      22                1
      23                3
      24                1

TABLE 3: VEHICLE_FEATURES_TABLE (vehicle_id is NOT unique but feature_id is unique per vehicle_id)
vehicle_id  |  feature_id
--------------|--------------
      22                1
      22                2
      23                1
      23                2
      23                6
      24                2
      24                6

like image 574
flukyspore Avatar asked Jun 07 '26 12:06

flukyspore


1 Answers

SELECT  SUM(lt.total_time) AS TOTAL_ALL,
        SUM(CASE WHEN (vft.feature_id IS NOT NULL) then LOG_TABLE.total_time else 0 end) AS FEATURE_TOTAL

FROM    VEHICLE_TABLE vt

        JOIN LOG_TABLE lt
        ON vt.vehicle_id = lt.vehicle_id

        LEFT JOIN VEHICLE_FEATURES_TABLE vft
        ON vt.vehicle_id = vft.vehicle_id AND vft.feature_id = 2

WHERE   vt.class_id = 1
like image 175
Tom Avatar answered Jun 09 '26 02:06

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!