简体   繁体   English

如何对总数据集的子查询求和以获得 sql 中的比例?

[英]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.此查询返回 14 个值,数据集中共有 20 个值。 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.当我尝试对此进行计数和求和时,它只返回 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 02Q Titan Airways泰坦航空公司

ontime table (only displaying relevant cells):准时表(仅显示相关单元格):

UniqueCarrier唯一运营商 arrDelay arr延迟
02Q 02Q -2 -2
02Q 02Q 10 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).数据集中共有 20 个运营商,但我正在查询平均延迟大于 10 分钟(结果为 14)的运营商。 I am not sure how to get the proportion of carriers using sql (14/20) = 0.7我不确定如何获得使用 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;和查询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:-即你的 14 出 20 然后比例返回为: -

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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