什么是雪花SQL中的PostgresSQL unnest()等价

时间:2020-04-21 13:03:55

标签: snowflake-cloud-data-platform unnest

如何在雪花中修改PostgresSQL?

UNNEST(array[
    'x' || to_char(date_trunc('MONTH', max(date)), 'Mon YYYY' ,
    'y' || to_char(date_trunc('MONTH', max(date)), 'Mon YYYY')
    )])

1 个答案:

答案 0 :(得分:0)

您可以使用“ flatten”从数组中分出值,然后使用“ table”将值转换为表:

-- Use an array for testing:
select array_construct(1, 2, 3, 4, 5);

-- Flattens into a table with metadata for each row:
select * from table(flatten(input => array_construct(1, 2, 3, 4, 5)));

--Pulls out just the values from the array:
select value::integer from table(flatten(input => array_construct(1, 2, 3, 4, 5)));

"::integer"部分将值强制转换为数组中所需的数据类型。它是可选的,但建议使用。

您可以通过创建用户定义的表函数来近似unnest的语法:

create or replace function UNNEST(V array)
returns table ("VALUE" variant)
language SQL
aS
$$
    select VALUE from table(flatten(input => V))
$$;

您会这样称呼它:

select * from table(unnest(array_construct(1, 2, 3, 4, 5)));

这将返回一个表,该表具有一个名为VALUE的类型为variant的单列。您可以创建一个返回字符串,整数等的版本。