如何在 window 上模拟 array_agg(distinct x)?
How do I simulate array_agg(distinct x) over window?
我有一个查询使用 array_agg
作为 window 函数,即带有 over (...)
子句。我只想在此数组聚合中获取一组不同的值,但这在 Postgres 9.4 中未实现:
对于以下(简化的)查询,
with test_data(day, daytime, song) as (
select 'MON', 'morning', 'A'
union all
select 'MON', 'morning', 'B'
union all
select 'MON', 'afternoon', 'A'
union all
select 'TUE', 'afternoon', 'B'
)
select distinct
day,
first_value(daytime) over w as started,
array_agg(distinct daytime) over w as daytimes,
array_agg(distinct song) over w as songs
from test_data
window w as (partition by day order by daytime ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING);
Postgres returns 以下内容:
SQLERROR [0A00]: ERROR: distinct is not implemented for window functions
我确定我无法避免使用 window 子句本身。我该如何解决这个限制?
我决定使用函数anyarray_uniq
as provided in this GitHub Repo。我将初始 select 包装在另一个 select
中,应用 anyarray_uniq
并按原样重用所有其他列。因为这正是我想要的,幸运的是在这种情况下我不需要考虑性能。
我有一个查询使用 array_agg
作为 window 函数,即带有 over (...)
子句。我只想在此数组聚合中获取一组不同的值,但这在 Postgres 9.4 中未实现:
对于以下(简化的)查询,
with test_data(day, daytime, song) as (
select 'MON', 'morning', 'A'
union all
select 'MON', 'morning', 'B'
union all
select 'MON', 'afternoon', 'A'
union all
select 'TUE', 'afternoon', 'B'
)
select distinct
day,
first_value(daytime) over w as started,
array_agg(distinct daytime) over w as daytimes,
array_agg(distinct song) over w as songs
from test_data
window w as (partition by day order by daytime ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING);
Postgres returns 以下内容:
SQLERROR [0A00]: ERROR: distinct is not implemented for window functions
我确定我无法避免使用 window 子句本身。我该如何解决这个限制?
我决定使用函数anyarray_uniq
as provided in this GitHub Repo。我将初始 select 包装在另一个 select
中,应用 anyarray_uniq
并按原样重用所有其他列。因为这正是我想要的,幸运的是在这种情况下我不需要考虑性能。