2015-11-02 115 views
1

我有一個使用array_agg作爲窗口函數的查詢,即使用over (...)子句。我想只得到一組在這個陣列整合不同的值,但這不是因爲Postgres的9.4的實現:如何在窗口上模擬array_agg(distinct x)?

對於下列(簡化)查詢,

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返回以下:

SQLERROR [0A00]: ERROR: distinct is not implemented for window functions 

我確定我無法避免使用window子句本身。我如何解決這個限制?

+0

http://dba.stackexchange.com/questions/89031/using-distinct-in-window-function-with-over –

+0

所以,你想讓歌曲在白天不同且有序嗎? –

回答

1

我決定使用GitHub Repo中提供的功能anyarray_uniq。我用另一個select封裝了最初的選擇,應用anyarray_uniq,並按原樣重新使用所有其他列。由於這正是我所尋找的,幸運的是我不需要在這種情況下考慮性能。