首页 > 解决方案 > 在 Google BigQuery 中使用 SQL 将字符串列转换为数字列

问题描述

我正在分析2018 年纽约市黄色汽车的出租车出行数据。(您需要一个 Google BigQuery 帐户才能访问此数据集。)

该模式表示大多数列都是数字的。但是,当我尝试计算关键美元数字(tip_amount、tolls_amount、total_amount)的总和时,我收到一条错误消息,指出它们是字符串变量。

SELECT sum(total_amount) 
FROM [bigquery-public-data:new_york_taxi_trips.tlc_yellow_trips_2018] 
WHERE month(dropoff_datetime) = 12

Error: Field total_amount is of type STRING which is not supported for SUM

然后我尝试使用 cast() 函数将其转换为数字变量,但这不起作用。

SELECT sum(total_amount_numeric) FROM 
(
     SELECT cast(total_amount as numeric) as total_amount_numeric 
     FROM [bigquery-public-data:new_york_taxi_trips.tlc_yellow_trips_2018]
     WHERE month(dropoff_datetime) = 12
)

Error: Field total_amount_numeric is of type STRING which is not supported for SUM

如何按我的意图分析这些数值变量,而不是在数据库中错误设置的字符串变量?

标签: sqlgoogle-bigquery

解决方案


您的查询将在标准 SQL 中按如下方式运行:

SELECT sum(total_amount_numeric)  
FROM (SELECT cast(total_amount as numeric) as total_amount_numeric 
      FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2018`
      WHERE EXTRACT(month FROM dropoff_datetime) = 12
     ) x;

您可以在查询之前包含此提示,以确保它使用标准 SQL 运行:

#standardSQL

推荐阅读