简体   繁体   English

BigQuery 的查询过滤器按 json 类型

[英]BigQuery's query filter by json type

My database table like below.我的数据库表如下。

Row Name名称 Info信息
1 1个 Tom汤姆 {"count":0, "error":[0,"failed",0]}
2 2个 Joe {"count":0, "error":["failed","failed","failed"]}
3 3个 Joe {"count":0, "error":[0,0,0]}
4 4个 Tom汤姆 {"count":0, "error":["failed","failed",0]}

I hope filter data by "Info.error's array" in the following order.我希望按以下顺序按“Info.error's array”过滤数据。

  1. all is 0全部为0
  2. exclude all failed排除所有失败
  3. at least one is 0至少一个是0

result data结果数据

Row Name名称 Info信息
1 1个 Tom汤姆 {"count":0, "error":[0,"failed",0]}
3 3个 Joe {"count":0, "error":[0,0,0]}
4 4个 Tom汤姆 {"count":0, "error":["failed","failed",0]}

So, how should enter the SQL syntax?那么,应该怎样输入SQL这个语法呢? Thanks a lot.非常感谢。

In order to find out the amount of a particular value in a json array you can use the following snippet:为了找出 json 数组中特定值的数量,您可以使用以下代码片段:

  (SELECT
    COUNTIF(JSON_EXTRACT_SCALAR(error) = "0")
  FROM
    UNNEST(JSON_EXTRACT_ARRAY(ex_table.Info, '$.error')) AS error ) count_zeros,
   
  (SELECT
    COUNTIF(JSON_EXTRACT_SCALAR(error) = "failed")
  FROM
    UNNEST(JSON_EXTRACT_ARRAY(ex_table.Info, '$.error')) AS error ) count_failed

Using these two new variables, you can then create your actual filters.使用这两个新变量,您可以创建实际的过滤器。

1. 1.

 WHERE
  count_zero = ARRAY_LENGTH(Info.error)
 WHERE 
  NOT count_failed = ARRAY_LENGTH(Info.error)
WHERE  
  count_zero > 0

You should be able to simplify your rule set as rule 3 accounts for all scenarios you have listed.您应该能够简化您的规则集,因为规则 3 说明了您列出的所有场景。 Given your sample data try the following:鉴于您的示例数据,请尝试以下操作:

select *,
from sample_data
WHERE "0" in (SELECT * from UNNEST(JSON_VALUE_ARRAY(info, "$.error")))

It produces:它产生:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM