2016-05-26 35 views
0

我有國家代碼座標表(用戶的軌跡),我有我的數據按日期排序。GROUP BY尊重值前後

user,coordinates, country 
1, place1, US 
1. place2, US 
1, place3, UK 
1, place4, UK 
1, place1, US 
2, place5, US 
2, place6, US 
2, place7, US 
2, place8, US 

我想這樣

1x "US, UK, US" ; 
1x "US", 

運動國家序列當我做GROUP BY我只是得到SEQ1爲 「美國,英國」。我需要在序列中擁有這些獨特的值,以瞭解用戶移動的位置。有沒有像這個排序序列中的前一行和下一行一樣的組版本?

+1

您需要一個指定排序的列。 –

回答

0

您需要一個指定順序的列,所以讓我假設一個存在。

select user, string_agg(country, ', ' order by ??) as countries 
from (select t.*, 
      lag(country) over (partition by user order by ??) as prev_country 
     from t 
    ) t 
where prev_country is null or country <> prev_country; 

只要指定正確的列訂購,其中??是。