简体   繁体   中英

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

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

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

It seems that there is not much point in putting both of them in one query unless you want the results together.
If so, just add a UNION between the 2 queries.

If you want to have both values in the same row try something like this:

SELECT (SELECT Sum(X) 
        FROM   TBL 
        WHERE  CLASS_ID = 1)       AS CLS_id1, 
       (SELECT Sum(X) 
        FROM   TBL 
        WHERE  CLASS_ID = 1 
               AND FEATURE_ID = 2) AS CLS_id1_FTR_ID2 

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