【问题标题】:CAST and REPLACE in Big QueryBig Query 中的 CAST 和 REPLACE
【发布时间】:2019-01-24 17:07:08
【问题描述】:

我的 BigQuery 表中有一个名为 Delivered_Cost 的列。对于没有成本的行,它有“-”。我想用 0 替换它,然后将该列转换为浮点数,以便我可以用它进行一些聚合。但是,当我使用下面的代码时,我遇到了问题。即使某些行有针对它们的值,它们也会更改为 null。如何编辑下面的代码,以便可以在同一个查询中替换和转换?

SQL 代码

SELECT Delivered_Cost,

REPLACE (Consideration_Set, "0", "Undefined") 为 Final_Consideration_Set, CAST(REPLACE(DELIVERED_COST, "-", "0") as float) as Final_Delivered,

来自 [桌子]

限制 100;

【问题讨论】:

    标签: google-bigquery


    【解决方案1】:

    这里的问题是数据中的千位分隔符(逗号)。您可以通过像这样更改查询来解决它(删除逗号):

    SELECT
      delivered_cost, 
      REPLACE(Consideration_Set, '0', 'undefined') Final_Consideration_Set, 
      CAST(REPLACE(REPLACE(DELIVERED_COST, ',',''), '-', '0') AS FLOAT) Final_Delivered
    FROM [table]
    

    此外,建议在 BigQuery 中使用标准 SQL,而不是旧版 SQL。您的查询的标准 SQL 版本是:

    #standardSQL
    SELECT
      delivered_cost, 
      REPLACE(Consideration_Set, '0', 'undefined') Final_Consideration_Set, 
      SAFE_CAST(REPLACE(REPLACE(DELIVERED_COST, ',',''), '-', '0') AS FLOAT64) Final_Delivered
    FROM `table`
    

    【讨论】:

      【解决方案2】:

      看起来您正在使用基于括号中的表引用的旧版 SQL。 转到选项并取消选中“使用旧版 SQL”的选项

      请参阅下面包含的 SQL。它对我有用。

      WITH table AS (
        SELECT
          '100.01' AS delivered_cost
          , 'News' AS consideration_set
        UNION ALL
        SELECT
          '-' AS delivered_cost
          , '0' AS consideration_set
      )
      SELECT
        delivered_cost
        , REPLACE(consideration_set, '0', 'undefined') final_consideration_set
        , SAFE_CAST(REPLACE(delivered_cost, '-', '0') AS FLOAT64) final_delivered_cost
      FROM table
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-18
        • 2020-11-03
        • 2018-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-01
        相关资源
        最近更新 更多