简体   繁体   中英

How to sum a subquery over total dataset to get a proportion in sql?

I need to get the proportion of the subquery over my total dataset, but am not sure how. This query returns 14 values and there are 20 values in the dataset total. How do I take the sum of this query and divide it by the total values in the dataset?

When I try to do count and sum of this, it just returns 1.0. I assume because it is taking the sum over the entire subquery value and not the entire dataset group that I need.

carriers table:

code carrier
02Q Titan Airways

ontime table (only displaying relevant cells):

UniqueCarrier arrDelay
02Q -2
02Q 10

There are a total of 20 carriers in the dataset, but I am querying for carriers with an average delay greater than 10 mins (which results in 14). I am not sure how to get the proportion of carriers using sql (14/20) = 0.7

select carriers.carrier, avg(arrDelay) from ontime, carriers
where carriers.code = ontime.UniqueCarrier
group by UniqueCarrier
having avg(arrDelay) between 10 and 30;

I believe that this might do what you wish:-

WITH 
    cte1 AS (SELECT  *, avg(arrDelay) AS avg_delay FROM carriers, ontime WHERE ontime.uniqueCarrier = carriers.code GROUP BY code HAVING avg_delay BETWEEN 10 AND 30),
    cte2 AS (SELECT (SELECT count(*) FROM cte1) / CAST((SELECT count(*) FROM carriers) AS FLOAT) AS proportion )
SELECT * FROM cte2;

For example with Carriers as:-

在此处输入图像描述

and the query SELECT *, avg(arrDelay) AS avg_delay FROM carriers, ontime WHERE ontime.uniqueCarrier = carriers.code GROUP BY code HAVING avg_delay BETWEEN 10 AND 30;

Returning:-

在此处输入图像描述

ie your 14 out of 20 then the proportion is returned as:-

在此处输入图像描述

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