如何将整数数组转换为行?

How can I convert the array of integers to rows?

我有一个 table 有:

id、时间戳、[整数数组]

如何将整数数组转换为行?几乎与array_agg相反。

例如,

1, ts, [1,2,3]
2, ts, [7,8,9]

会是

1, ts, 1
1, ts, 2
1, ts, 3
2, ts, 7
2, ts, 8
2, ts, 9

我已通读 https://docs.snowflake.net/manuals/sql-reference/udf-js-table-functions.html,但尚不清楚这是否有效。我试图避免在数据库之外使用脚本语言。谢谢!

使用FLATTEN。它有各种选项,包括字段值、数组中的索引等。

下面是一个完整的例子:

create or replace table x(i int, s string, v variant);
insert into x 
select column1, column2, parse_json(column3) from values
  (1, 'ts1', '[1,2,3]'),
  (2,'ts2','[7,8,9]');

select * from x;
---+-----+------+
 I |  S  |  V   |
---+-----+------+
 1 | ts1 | [    |
   |     |   1, |
   |     |   2, |
   |     |   3  |
   |     | ]    |
 2 | ts2 | [    |
   |     |   7, |
   |     |   8, |
   |     |   9  |
   |     | ]    |
---+-----+------+

select i, s, f.value as newcolumn from x, table(flatten(x.v)) f;
---+-----+-----------+
 I |  S  | NEWCOLUMN |
---+-----+-----------+
 1 | ts1 | 1         |
 1 | ts1 | 2         |
 1 | ts1 | 3         |
 2 | ts2 | 7         |
 2 | ts2 | 8         |
 2 | ts2 | 9         |
---+-----+-----------+