计算使用 SQL Server 满足条件的各种类别的百分比



我有一个表格,其中包含有关城市之间航班的信息,如下所示:

    origin_city dest_city   time    
    Dothan AL   Atlanta GA    171    
    Dothan AL   Atlanta GA    171    
    Dothan AL   Elsewhere AL    2    
    Dothan AL   Elsewhere AL    2    
    Dothan AL   Elsewhere AL    2    
    Boston MA   New York NY     5    
    Boston MA   City MA         1    
    New York NY Boston MA       5    
    New York NY Boston MA       5    
    New York NY Boston MA       5    
    New York NY Poughkipsie NY  2

我想找出每个始发城市的航班长度少于 3 小时的百分比。所以结果将是这样的:

    Dothan AL    60
    Boston MA    50
    New York NY  25

我认为可以工作的代码如下所示:

     SELECT F.origin_city as origin_city,    
       ((SELECT COUNT(*) FROM Flights as F2
       WHERE F2.actual_time < 3) / (SELECT COUNT(*) FROM Flights as  F3)) * 100
     AS percentage
     FROM Flights as F
     GROUP BY F.origin_city
     ORDER BY percentage;
     GO

当我运行它时,我得到了一个原始城市列表和一个百分比列,正如预期的那样,但百分比始终为 0。我仍然对子查询感到非常困惑(如您所见)。

我会使用 AVG() 作为窗口函数来做到这一点:

SELECT F.origin_city as origin_city, 
       AVG( CASE WHEN F2.actual_time < 3 THEN 100.0 ELSE 0 END) as percentage
FROM Flights F
GROUP BY F.origin_city
ORDER BY percentage;

这假定时间以小时为单位。 根据谷歌地图,你可以在68小时内从多森步行到亚特兰大,所以171是可疑的。

您的百分比是针对整个表格,而不是按原产地城市分组的百分比。尝试这样的事情:

 SELECT F.origin_city as origin_city,    
   (SUM(CASE WHEN F.actual_time < 3 THEN 1 ELSE 0 END) / COUNT(*) )  * 100 AS percentage
 FROM Flights as F
 GROUP BY F.origin_city
 ORDER BY percentage;
 GO

FWIW 当前子查询的问题是当前行与子查询中的数据之间没有联接。你可以把它改写成这样:

 SELECT F.origin_city as origin_city,    
 ((SELECT COUNT(*) FROM Flights as F2
 WHERE F2.origin_city = F.origin_city and F2.actual_time < 3) / (SELECT COUNT(*) FROM Flights as  F3 where F3.origin_city = F.origin_city)) * 100
 AS percentage
 FROM Flights as F
 GROUP BY F.origin_city
 ORDER BY percentage;
 GO

但是,当您已经有足够的数据来进行计算时,没有必要重新查询表中的每一行,如上所示。

相关内容

  • 没有找到相关文章

最新更新