我正在尝试打印来自不同站点的 ID 和名称以及该站点的总乘车次数。
ID 和姓名来自
stations
表,而旅行次数来自 trips
表,所以我创建了一个如下形式的查询:
SELECT id, name and num_rides
FROM (SELECT COUNT (*) num_rides
FROM tableB AS b) AS num_rides
INNER JOIN tableA AS a ON a.station_id = b.start_station_id
问题是外部查询的 JOIN 语句无法识别我的表的
b
别名,我在内部查询中为其添加了别名。
我尝试单独运行查询,它们都工作正常。
为什么计算机不记得我在外部查询中的内部查询别名?
错误:
Unrecognized name: trips
,trips 是我用于表 B 的别名。
SELECT
station_id,
name,
num_of_rides AS num_of_rides_starting_at
FROM
(
SELECT
start_station_id,
COUNT(*) number_of_rides
FROM
bigquery-public-data.new_york_citibike.citibike_trips AS trips
GROUP BY
trips.start_station_id
)
AS num_of_rides
INNER JOIN
bigquery-public-data.new_york_citibike.citibike_stations AS stations
ON stations.station_id = trips.start_station_id
ORDER BY num_of_rides DESC
我认为问题在于“旅行”别名仅在括号内有效。尝试命名整个 select 语句并引用该名称。
SELECT
station_id,
name,
num_of_rides AS num_of_rides_starting_at
FROM
(
SELECT
start_station_id,
COUNT(*) number_of_rides
FROM
bigquery-public-data.new_york_citibike.citibike_trips AS trips
GROUP BY
trips.start_station_id
) NeedNameHere
AS num_of_rides
INNER JOIN
bigquery-public-data.new_york_citibike.citibike_stations AS stations
ON stations.station_id = NeedNameHere.start_station_id
ORDER BY num_of_rides DESC
SELECT
station_id, /*from table: citibike_stations */
name, /*from table: citibike_trips */
number_of_rides AS number_of_rides_starting_at_station /*from table: station_num_trips*/
FROM
(SELECT
start_station_id,
COUNT(*) number_of_rides
FROM `bigquery-public-data.new_york_citibike.citibike_trips`
GROUP BY start_station_id
)
AS station_num_trips
INNER JOIN `bigquery-public-data.new_york_citibike.citibike_stations`
ON station_id = start_station_id
ORDER BY number_of_rides DESC