查询雪花中数组的子集

时间:2021-07-06 23:26:47

标签: sql snowflake-cloud-data-platform

我正在尝试根据我的一列中的数组元素对雪花中的 SQL 查询进行子集化,但不知道该怎么做。

例如,如果 column2 是一个看起来像这样的数组数据类型

SELECT column2
FROM table
LIMIT 7;

带输出:


Row column2
1 ["cats","dogs"]
2 ["horses","cows","cats"]
3 NULL
4 ["dogs","fish]
5 ["birds"]
6 ["cats"]
7 NULL

我想对数据进行子集化并运行一个查询,该查询在第 2 列中的任何数组中将“cats”作为元素的任何行中提取-因此第 1、2 和 6 行-我将如何构建该查询查询?

使用这样的东西是行不通的:

SELECT column1, column2, column3
FROM Table
WHERE column2 = "cats" (or using an IN statement)

并导致错误消息作为无效标识符“cats”,因为它在数组中,所以我期望它

任何见解将不胜感激!

3 个答案:

答案 0 :(得分:3)

你想要array_contains()

where array_contains('cats'::variant, column2)

答案 1 :(得分:3)

ARRAY_CONTAINS() 有效,但您必须小心类型。

例如,这个返回false:

select array_contains('2020-01-01'::date::variant
    , array_construct('2020-01-01', '2019-01-01'));

但这些返回 true:

select array_contains('2020-01-01'::date::string::variant
    , array_construct('2020-01-01', '2019-01-01'));


select array_contains('2020-01-01'::date::variant
    , array_construct('2020-01-01'::date, '2019-01-01'));

在字符串的情况下,这个返回一个编译错误(如你所见):

select array_contains('cats'
    , array_construct('cats', 'dogs'));

-- SQL compilation error: error line 1 at position 7 Invalid argument types for function 'ARRAY_CONTAINS': (VARCHAR(4), ARRAY)

但是这个修复了它:

select array_contains('cats'::variant
    , array_construct('cats', 'dogs'));

答案 2 :(得分:0)

array_contains 可以让您回答您的具体问题,但我认为了解如何将数组转换为看起来更像表格的内容可能会很有用。

如果您使用数组,雪花中的横向 flatten 函数绝对值得一试。

enter image description here

with cte as (
  select 'some other info_1' col_1 ,ARRAY_CONSTRUCT('cats','dogs') col_2  
union select 'some other info_2' col_1 ,ARRAY_CONSTRUCT('horses','cows','cats')
union select 'some other info_3' col_1 ,NULL
union select 'some other info_4' col_1 ,ARRAY_CONSTRUCT('dogs','fish')
union select 'some other info_5' col_1 ,ARRAY_CONSTRUCT('birds')
union select 'some other info_6' col_1 ,ARRAY_CONSTRUCT('cats')
union select 'some other info_7' col_1 ,NULL )

select col_1, animals.value from cte ,lateral flatten(col_2) animals 
where animals.value = 'cats';