【问题标题】:BigQuery SQL syntax error FOR function ("Syntax error: Expected ")" but got keyword FOR at [7:18]")BigQuery SQL 语法错误 FOR 函数(“语法错误:预期的”)“但在 [7:18] 获得关键字 FOR”)
【发布时间】:2020-01-03 18:25:07
【问题描述】:

我需要根据 dev_id 在一列 (cont_url) 中连接数据。我能够使用此查询在 MS-SQL 中成功执行此操作,但我需要在 BigQuery 中执行此操作。

select
    dev_id,
    stuff(
    (SELECT '|||' + cont_url
      FROM `test_table_sample`
        WHERE  dev_id = a.dev_id
         FOR XML PATH (''))                --Error is here
        , 1, 1, '') as testlist
from
    `test_table_sample` as a
group by
    dev_id

当我在 Big Query 中安装表并尝试运行相同的查询时,出现语法错误。

预期为“)”,但在 [7:18] 得到关键字 FOR

我不知道我做错了什么以及 BigQuery 标准 SQL 语法与 T-SQL 有何不同。

我已经包含了一个示例数据表。

test_table_sample
dev_id  cont_url
Device1 Link1
Device1 Link2
Device1 Link3
Device1 Link4
Device2 anotherLink1
Device2 anotherLink2
Device2 anotherLink3
Device2 anotherLink4
Device2 anotherLink5

这是查询的结果。

Results 
dev_id  cont_url
Device1 Link1|||Link2|||Link3|||Link4
Device2 anotherLink1|||anotherLink2|||anotherLink3|||anotherLink4|||anotherLink5

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    BigQuery 允许您只聚合字符串。语法要简单得多:

    select dev_id, string_agg(cont_url, '|||') as testlist
    from `test_table_sample` as a
    group by dev_id;
    

    也就是说,我强烈建议您改用数组:

    select dev_id, array_agg(cont_url) as testlist
    from `test_table_sample` as a
    group by dev_id;
    

    比笨拙的分隔字符串要好得多。

    【讨论】:

    • 您好,非常感谢您的回答。我想没有办法将 url 数据放在一个单元格中(我将计算唯一的用户路径,并希望每个用户将所有链接放在一个单元格中)
    • @Putnik 。 . . string_agg() 执行您在 SQL Server 中明确执行的操作。 array_agg() 可能更可取。
    • 如果你好奇的话,两个都做!他们使用相同的聚合。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2022-11-10
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多