我想知道如何在Redshift中将逗号分隔的值转换为行。恐怕我自己的解决方案不是最佳的。请指教。我有带有逗号分隔值的列之一的表。例如:
我有:
user_id|user_name|user_action
-----------------------------
1 | Shone | start,stop,cancell...
我想看看
user_id|user_name|parsed_action
-------------------------------
1 | Shone | start
1 | Shone | stop
1 | Shone | cancell
....
最佳答案
对现有答案的一点改进是使用第二个“数字”表,该表枚举了所有可能的列表长度,然后使用cross join
使查询更紧凑。
我知道,Redshift没有创建数字表的简单方法,但是我们可以使用https://www.periscope.io/blog/generate-series-in-redshift-and-mysql.html的一些技巧来使用行号创建一个数字表。
具体来说,如果我们假设cmd_logs
中的行数大于user_action
列中的最大逗号数,则可以通过对行进行计数来创建数字表。首先,假设user_action
列中最多有99个逗号:
select
(row_number() over (order by true))::int as n
into numbers
from cmd_logs
limit 100;
如果我们想花哨的话,我们可以从
cmd_logs
表中计算逗号的数量,以便在numbers
中创建更精确的行集:select
n::int
into numbers
from
(select
row_number() over (order by true) as n
from cmd_logs)
cross join
(select
max(regexp_count(user_action, '[,]')) as max_num
from cmd_logs)
where
n <= max_num + 1;
一旦有了
numbers
表,我们可以执行以下操作:select
user_id,
user_name,
split_part(user_action,',',n) as parsed_action
from
cmd_logs
cross join
numbers
where
split_part(user_action,',',n) is not null
and split_part(user_action,',',n) != '';
关于amazon-web-services - Redshift 。将逗号分隔的值转换为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25112389/