我有时间戳数据,想要从一列创建一个列表,相邻的重复项(但不是所有重复项)都折叠成一列。
例如,给出以下数据:
'2001-01-01 00:00:01' 'a'
'2001-01-01 00:00:02' 'a'
'2001-01-01 00:00:03' 'b'
'2001-01-01 00:00:04' 'b'
'2001-01-01 00:00:05' 'b'
'2001-01-01 00:00:06' 'a'
'2001-01-01 00:00:07' 'a'
'2001-01-01 00:00:08' 'c'
'2001-01-01 00:00:09' 'a'
- 我希望结果为'a','b','a','c','a'
。
我正在使用Snowflake,它有listagg(distinct foo)
和listagg(distinct foo) within group(order by bar)
甚至是listagg(distinct foo) within group(order by bar) over(partition by baz)
,但我没有找到办法来做我需要的事情(Google也没有帮助) 。我真的非常想避免使用join
。
如果你知道另一个有listagg
或group_concat
的方言的解决方案,请发布,我会尝试将其翻译为Snowflake供我使用。非常感谢。
不能工作的事情:
trim(regexp_replace('~' || listagg(foo, '~') || '~', '~([^~]+~)\\1', '~\\1'), '~')
,但Snowflake在匹配模式中不允许\1
:我收到错误Invalid regular expression: '~([^~]+~)\1', invalid escape sequence: \1
。listagg(iff(lag(foo) ignore nulls over(partition by baz order by bar)=foo, null, foo), ',') within group(order by bar) over(partition by baz)
但收到了错误Window function [LAG(...)] may not be nested inside another window function.
答案 0 :(得分:0)
不幸的是,我不认为Snowflake支持正则表达式模式中的反向引用。
可能的解决方案:
例如使用LAG消除输入流中的重复项
with sub as (select foo, bar, lag(bar) over (order by foo) barlag)
select listagg(foo) within group order by (bar) from foo
where barlag is null or barlag <> lag;
使用LISTAGG,但编写一个JavaScript UDF来拆分LISTAGG的结果并消除其中的重复项