【问题标题】:Query to count all records without certain key in the json column of the snowflake table查询统计雪花表的json列中所有没有特定key的记录
【发布时间】:2021-09-23 18:18:40
【问题描述】:

我正在尝试从雪花中获取记录数,而该特定记录的 json 列中没有特定键。

雪花桌是这样的:

EMP_ID|DEPARTMENT_NAME|EID|DETAILS
EMP10001 | Finance |10008918 |{                                                                                 
"name": "Alec George",                                                        
"Year_Joined": "2013",
"Ready_to_transfer":  "no",
"Ready_to_permanently_WFH":  "yes",
}

现在我想在雪花表的详细信息列中计算没有以 Ready_ 开头的键的记录,并按 Department_Name 分组计数。

注意:详细信息中可以有多个以Ready_开头的键。

目前发生的情况是我的计数查询返回的记录也列出了以 Ready_ 开头的键。

【问题讨论】:

  • 我认为最简单的方法可能是将 json 视为文本并搜索该序列。选择 json NOT RLIKE 'Ready_to' 所在的行。查找路径有更复杂的方法,但我不知道您是否需要一种方法。

标签: json count snowflake-cloud-data-platform json-flattener


【解决方案1】:

你可以扁平化得到所有的键,然后对于每条记录你可以计算以你想要的字符串开头的键的数量:

with data as (
select $1 emp_id, $2 dep, $3 eid, parse_json($4) details
from (values
('EMP10001','Finance', 10008918, '{
"name": "Alec George",
"Year_Joined": "2013", "Ready_to_transfer": "no", "Ready_to_permanently_WFH": "yes", }')
,('EMP10002','Finance', 10008918, '{
"name": "Alex George",
"Year_Joined": "2013", }')
)
)

select seq, count_if(detail.key like 'Ready_%') how_many_ready
from data, table(flatten(details)) detail
group by 1
;

那么你只需要计算计数> 0的元素的#个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-16
    • 2023-02-15
    • 2018-01-02
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多