这让我伤透了脑筋。在 Snowflake 中,我的字段
city_info
看起来像(对于 3 个样本记录)
[{"name": "age", "content": 35}, {"name": "city", "content": "Chicago"}]
[{"name": "age", "content": 20}, {"name": "city", "content": "Boston"}]
[{"name": "city", "content": "New York"}, {"name": "age", "content": 42}]
我尝试从中提取一列
city
Chicago
Boston
New York
我试着把它压平
select *
from lateral flatten(input =>
select city_info::VARIANT as event
from data
)
从那里我可以导出该值,但这只允许我对 1 行执行此操作(所以我必须添加
limit 1
,这是没有意义的,因为我的所有行都需要这个)。
如果我尝试对 3 行执行此操作,它会告诉我
subquery returns more than one row.
你可以写成:
SELECT value:content::string AS city_name
FROM tab,
LATERAL FLATTEN(input => tab.city_info)
WHERE value:name::string = 'city';
使用高阶函数的替代方法FILTER:
CREATE TABLE tab(col VARIANT) AS
SELECT [{'name':'age', 'content': 35},{'name':'city', 'content': 'Chicago'}] UNION
SELECT [{'name':'age', 'content': 20},{'name':'city', 'content': 'Boston'}] UNION
SELECT [{'name':'city', 'content': 'New York'},{'name':'age', 'content': 42}];
查询:
SELECT *, FILTER(col, x -> x:name::TEXT ILIKE 'City')[0]:content::TEXT
FROM tab;
输出: