首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >红移。将逗号分隔的值转换为具有所有组合的行

红移。将逗号分隔的值转换为具有所有组合的行
EN

Stack Overflow用户
提问于 2017-07-10 17:12:16
回答 1查看 508关注 0票数 0

我有:

代码语言:javascript
运行
复制
user_id|user_name|user_action
-----------------------------
1      | Shone   | start,stop,cancell

我希望看到:

代码语言:javascript
运行
复制
user_id|user_name|parsed_action 
------------------------------- 
1      | Shone   | start 
1      | Shone   | start,stop 
1      | Shone   | start,cancell
1      | Shone   | start,stop,cancell       
1      | Shone   | stop         
1      | Shone   | stop,cancell
1      | Shone   | cancell      
....
EN

Stack Overflow用户

发布于 2017-07-10 19:47:46

您可以创建以下Python UDF:

代码语言:javascript
运行
复制
create or replace function get_unique_combinations(list varchar(max))
returns varchar(max)
stable as $$

from itertools import combinations

arr = list.split(',')

response = []

for L in range(1, len(arr)+1):
    for subset in combinations(arr, L):
        response.append(','.join(subset))

return ';'.join(response)

$$ language plpythonu;

这将获取您的操作列表,并返回用分号分隔的唯一组合(组合中的元素本身将用逗号分隔)。然后使用UNION hack将值拆分为单独的行,如下所示:

代码语言:javascript
运行
复制
WITH unique_combinations as (
    SELECT 
     user_id
    ,user_name
    ,get_unique_combinations(user_actions) as action_combinations
    FROM your_table
)
,unwrap_lists as (
    SELECT 
     user_id
    ,user_name
    ,split_part(action_combinations,';',1) as parsed_action
    FROM unique_combinations
    UNION ALL
    SELECT 
     user_id
    ,user_name
    ,split_part(action_combinations,';',2) as parsed_action
    FROM unique_combinations
    -- as much UNIONS as possible combinations you have for a single element, with the 3rd parameter (1-based array index) increasing by 1
    )
SELECT *
FROM unwrap_lists
WHERE parsed_action is not null
票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45008045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档