[英]How can I split a string into character in Snowflake?
I need to split a string like "abc" into individual records, like "a", "b", "c".我需要将像“abc”这样的字符串拆分成单独的记录,比如“a”、“b”、“c”。
This should be easy in Snowflake: SPLIT(str, delimiter)
这在雪花中应该很容易:
SPLIT(str, delimiter)
But if the delimiter is null, or an empty string I get the full str
, and not characters as I expected.但是,如果分隔符是 null 或空字符串,我会得到完整的
str
,而不是我预期的字符。
create or replace function split_string_to_char(a string)
returns array
as $$
split(regexp_replace(a, '.', ',\\0', 2), ',')
$$
;
select split_string_to_char('hello');
I found this problem while working on Advent of Code 2020 .我在处理Advent of Code 2020时发现了这个问题。
Instead of just splitting a string a working solution is to add commas between all the characters, and then split that on the commas:一个可行的解决方案不仅仅是拆分字符串,而是在所有字符之间添加逗号,然后在逗号上拆分:
select split(regexp_replace('abc', '.', ',\\0', 2), ',')
If you want to create a table out of it:如果你想用它创建一个表:
select *
from table(split_to_table(regexp_replace('abc', '.', ',\\0', 2), ',')) y
As seen on https://github.com/fhoffa/AdventOfCodeSQL/blob/main/2020/6.sql如https://github.com/fhoffa/AdventOfCodeSQL/blob/main/2020/6.sql上所见
In addition to Felipe's approach, you could also use a JavaScript UDF:除了 Felipe 的方法,您还可以使用 JavaScript UDF:
create function TO_CHAR_ARRAY(STR string)
returns array
language javascript
as
$$
return STR.split('');
$$;
select to_char_array('hello world');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.