我正在使用来自bigquery的citibike信息,目前正在学习子查询。我对每个站点可用的自行车数量进行平均,然后尝试从平均值中减去每个站点可用的自行车数量(以获得差值)。
我的代码如下:
SELECT
name,
station_id,
num_bikes_available,
(num_bikes_available) - (AvailableAverage) AS Difference,
(SELECT AVG(num_bikes_available)
FROM `bigquery-public-data.new_york.citibike_stations`) AS AvailableAverage,
FROM
`bigquery-public-data.new_york.citibike_stations`
ORDER BY
num_bikes_available DESC;
之前,我的查询是这样的:
SELECT
name,
station_id,
num_bikes_available,
(SELECT AVG(num_bikes_available)
FROM `bigquery-public-data.new_york.citibike_stations`) AS AvailableAverage,
FROM
`bigquery-public-data.new_york.citibike_stations`
ORDER BY
num_bikes_available DESC;
并且运行良好。
现在它说它无法识别别名
AvailableAverage
,我不知道为什么。
我尝试对查询进行排序,以便子查询出现在差异行之前,但它仍然无法识别它(这里似乎顺序并不重要)。
我不懂子查询吗?或者是混叠部分?
请参阅我对“为什么”的评论
同时,下面是快速、简单的“修复”
SELECT
name,
station_id,
num_bikes_available,
num_bikes_available - AvailableAverage AS Difference,
AvailableAverage,
FROM `bigquery-public-data.new_york.citibike_stations` ,
(SELECT AVG(num_bikes_available) AS AvailableAverage
FROM `bigquery-public-data.new_york.citibike_stations`)
ORDER BY num_bikes_available DESC;