Bigquery - 如何将float浮动到字符串w / o向上/向下舍入?

时间:2017-02-07 21:34:07

标签: google-bigquery

基本上我有一批GPS坐标(lat和long),我希望有一个格式为" lat; long"的字符串。我做的是:

CONCAT(CAST(Latitude AS STRING),";", CAST(Longitude AS STRING))

但遇到了一个问题,其中坐标被CAST四舍五入(STRING()做了同样的事情)。例如,select CAST(45.3618927 as STRING)我将获得45.3619。我怎样才能防止这种舍入?

注意:我知道标准SQL中的SAFE_CAST给了我我想要的东西,但由于其他原因,我必须使用Legacy方言。

1 个答案:

答案 0 :(得分:2)

#legacySQL
SELECT CONCAT(
  RTRIM(CONCAT(LEFT(lat_temp, lat_pos - 1), '.', SUBSTR(lat_temp, lat_pos)), '0'), 
  ';',
  RTRIM(CONCAT(LEFT(lon_temp, lon_pos - 1), '.', SUBSTR(lon_temp, lon_pos)), '0') 
  ) AS lat_lon
FROM (
  SELECT 
    INSTR(STRING(lat * 1000000), '.') - 6 AS lat_pos, 
    REPLACE(STRING(lat * 1000000),'.', '') AS lat_temp,
    INSTR(STRING(lon * 1000000), '.') - 6 AS lon_pos, 
    REPLACE(STRING(lon * 1000000),'.', '') AS lon_temp
  FROM 
    (SELECT 34.052235 AS lat, -118.243683 AS lon) AS yourTable
)   

当然看起来很难看,但正如你所说 - 出于某种原因,你想坚持使用传统的SQL 否则请参阅下面的标准SQL版本

#standardSQL
WITH yourTable AS (
  SELECT 34.052235 AS lat, -118.243683 AS lon
)
SELECT CONCAT(CAST(lat AS STRING),";", CAST(lon AS STRING)) AS lat_lon
FROM yourTable  

旧版SQL的另一个(不太丑陋)版本是使用JS UDF

#legacySQL 
SELECT lat, lon, lat_lon
FROM (JS(
  -- input table
  (
    SELECT lat, lon FROM
    (SELECT 34.052235 AS lat, -118.243683 AS lon) AS yourTable
  ),
  -- input vars
  lat, lon, 
  -- output schema
  "[
    {name: 'lat_lon', type: 'STRING'},
    {name: 'lat', type: 'FLOAT'},
    {name: 'lon', type: 'FLOAT'}
    ]",
  -- the function
  "function(row, emit) {
    emit({
      lat_lon: row.lat.toString().concat(';').concat(row.lon.toString()),
      lat: row.lat,
      lon: row.lon
    })
  }"
))  

最后,如果偶然 - 你将决定迁移到Standard SQL,使用FORMAT可以让生活变得更轻松(感谢Elliott对此发表评论)

#standardSQL 
SELECT FORMAT('%t;%t', lat, lon) AS lat_lon 
FROM
  (SELECT 34.052235 AS lat, -118.243683 AS lon) AS yourTable