SQL中如何划分两个不同查询的结果?

问题描述

查询编号 1:

SELECT starting_location,count(starting_location) as POPULARLOCATION
FROM trips
GROUP BY starting_location
ORDER by POPULARLOCATION DESC

查询编号 2:

SELECT starting_location,count(starting_location) as CIRculaRTRIP
FROM trips
WHERE starting_location = ending_location
GROUP BY starting_location
ORDER by CIRculaRTRIP DESC

我想了解每个起始位置的循环旅行占旅行的百分比。如何将第二个查询的结果除以第一个查询的结果?

解决方法

一种方式是这样的:

SELECT starting_location
  count(*) as POPULARLOCATION,count(case when starting_location = ending_location then 1 else null end) as CIRCULARTRIP,count(case when starting_location = ending_location then 1 else null end) * 100.00 / count(starting_location)  as percentage
FROM trips
GROUP BY starting_location
,

使用条件聚合。要得到比例,我觉得最简单的方法是:

SELECT starting_location,COUNT(*) as POPULARLOCATION,AVG(CASE WHEN starting_location = ending_location THEN 1.0 ELSE 0 END) as circular_ratio
FROM trips
GROUP BY starting_location
ORDER by POPULARLOCATION DESC