GROUP BY尊重值

时间:2016-05-26 00:08:10

标签: sql postgresql

我有国家代码的坐标表(用户的轨迹),按日期排序我的数据。

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作为"美国,英国和#34;。我需要在序列中包含这些唯一值,以了解用户移动的位置。是否存在类似于版本的组件,它遵循此排序序列中的上一行和下一行?

1 个答案:

答案 0 :(得分: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;

只需为??所在的位置指定正确的列。