繁体   English   中英

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

[英]How can I convert the array of integers to rows?

我有一张桌子,上面有:

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         |
---+-----+-----------+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM