BigQuery的StandardSQL NTH()和FIRST()函数

时间:2017-05-02 09:28:47

标签: sql google-bigquery

我从BigQuery开始,在pSQl方面有一些经验。 我正在成功运行的#legacySQL查询是:

SELECT
    FIRST(SPLIT(ewTerms, '/')) AS place,
    NTH(2, SPLIT(ewTerms, '/')) AS divisor
FROM (SELECT ewTerms FROM account.free)

表'free'中'ewTerms'列中的字符串值是单个数字分数,例如“2/4”,“3/5”等。这个#legacySQl查询从'ewTerms成功创建两列',阅读:

Row place divisor
1   3   5
2   2   4

我现在需要在WITH函数中使用此列创建,因此我必须切换到使用#standardSQL。 谁能告诉我如何使用#standardSQL调用字符串的FIRST()和NTH()函数?我试过了:

WITH prep AS(
        SELECT 
            SPLIT(ewTerms, '/') AS split
        FROM (SELECT ewTerms FROM accounts.free)
    )

SELECT 
    split[SAFE_ORDINAL(1)] AS place,
    split[SAFE_ORDINAL(2)] AS divisor
FROM prep

但这是错误的。帮助任何人?

1 个答案:

答案 0 :(得分:1)

你的问题不清楚是什么问题。此查询适用于我:

#standardSQL
WITH Input AS (
  SELECT '3/5' AS ewTerms UNION ALL
  SELECT '2/4' AS ewTerms
), prep AS (
  SELECT 
    SPLIT(ewTerms, '/') AS split
  FROM Input
)
SELECT 
  split[SAFE_ORDINAL(1)] AS place,
  split[SAFE_ORDINAL(2)] AS divisor
FROM prep;

输出结果为:

+-------+---------+
| place | divisor |
+-------+---------+
| 2     | 4       |
| 3     | 5       |
+-------+---------+

使用原始表格,您的查询将是:

#standardSQL
WITH prep AS (
  SELECT 
    SPLIT(ewTerms, '/') AS split
  FROM accounts.free
)
SELECT 
  split[SAFE_ORDINAL(1)] AS place,
  split[SAFE_ORDINAL(2)] AS divisor
FROM prep;