Google bigquery 使用BQ命令执行BQ查询时导致问题的查询案例

Google bigquery 使用BQ命令执行BQ查询时导致问题的查询案例,google-bigquery,Google Bigquery,我正试图使用bq命令通过bash执行查询。当通过web UI以及通过app script@script.google.com执行查询时,查询工作正常。然而,当作为一个简单的bash执行时(或者仅仅通过cmd提示符),我会不断收到一个“语法错误:意外的关键字,然后在[1:393]”。第393列是指语句的中间部分。我已经做了大量的搜索,无法找出我做错了什么(因为查询在其他地方工作)。是否有人可以就导致错误的原因提供建议 bq query --destination_table abcdefcloud

我正试图使用
bq
命令通过bash执行查询。当通过web UI以及通过app script@script.google.com执行查询时,查询工作正常。然而,当作为一个简单的bash执行时(或者仅仅通过cmd提示符),我会不断收到一个
“语法错误:意外的关键字,然后在[1:393]”
。第393列是指语句的中间部分。我已经做了大量的搜索,无法找出我做错了什么(因为查询在其他地方工作)。是否有人可以就导致错误的原因提供建议

bq query --destination_table abcdefcloud:ds_tables.daily_over_frequency_output
    --replace --use_legacy_sql=false 'with freq as
    (select month as month,campaign_id,campaign,case when  freq = '1' then 'a'
     when freq = '2' then 'b'
     when freq = '3-6' then 'c'
     when freq = '7-9' then 'd'
     when freq = '10-19' then 'e'
     when freq = '20-29' then 'f'
     when freq = '30-39' then 'g'
     when freq = '40-49' then 'h'
     when freq = '50-59' then 'i'
     when freq = '60-69' then 'j'
     when freq = '70-79' then 'k'
     when freq = '80-89' then 'l'
     when freq = '90-99' then 'm'
     when freq = '100+' then 'n'
     else 'other' end as sort,
     freq,sum(imps) as imps,sum(uu) as uu from...

非常感谢你的帮助。Brian P

假设

freq
列是数字列(可能应该是),那么您的
CASE
表达式应该失败,因为
3-6
不是有效数字。请尝试此版本:

case
    when freq = 1 then 'a'
    when freq = 2 then 'b'
    when freq between 3 and 6 then 'c'
    when freq between 7 and 9 then 'd'
    when freq between 10 and 19 then 'e'
    when freq between 20 and 29 then 'f'
    ...
    when freq > 100 then 'n'
    else 'other' end as sort

我认为这是你的问题:

freq = '1' then 'a'
如果仔细查看引号,您会注意到它们与用于引用查询的类型相同:)这最终会被计算为类似于:

freq = then

。。。我认为这不是你想要的。如果改为使用双引号,它应该“正常工作”,减去查询中的任何语义错误。

这里的问题是由于在查询中使用了相同的单引号,这些单引号与您包装整个查询时使用的引号相同

您的选择:

  • 当freq=\'1\'然后是'a\'
  • 当freq=“1”然后是“a”时,将引号更改为双引号
  • 改为通过文件将查询传递给bq查询命令
    cat your_query.sql | bq query
  • 选项3:是最优雅的解决方案,也有助于以一种良好的方式组织代码,使SQL保持为SQL,而不是将大量SQL直接嵌入到bash代码中。您不需要对当前SQL进行任何更改

    完整的示例如下所示

    cat your_query.sql | bq query \
      --destination_table abcdefcloud:ds_tables.daily_over_frequency_output \
      --replace \
      --use_legacy_sql=false 
    
    其中
    您的_query.sql
    将包含:

    with freq as
    (select month as month,campaign_id,campaign,case when  freq = '1' then 'a'
     when freq = '2' then 'b'
     when freq = '3-6' then 'c'
     when freq = '7-9' then 'd'
     when freq = '10-19' then 'e'
     when freq = '20-29' then 'f'
     when freq = '30-39' then 'g'
     when freq = '40-49' then 'h'
     when freq = '50-59' then 'i'
     when freq = '60-69' then 'j'
     when freq = '70-79' then 'k'
     when freq = '80-89' then 'l'
     when freq = '90-99' then 'm'
     when freq = '100+' then 'n'
     else 'other' end as sort,
     freq,sum(imps) as imps,sum(uu) as uu from...
    

    非常感谢布莱基。没有意识到案例中的引用可能会导致问题。喜欢你关于通过文件调用查询的建议。工作起来很有魅力:)是的,这确实是问题所在:)将单引号改为双引号确实解决了问题:)