将多行汇总为一

时间:2018-07-26 14:50:03

标签: sql amazon-redshift

这是数据的样子:

   master_id id states
    1         1  NJ, PA, IL
    1         2  IL, NJ, NY, CA
    1         3  MA, DC

我正在尝试获取master_id级别的状态摘要(注意,已删除NJ和IL的重复项),即:

master_id states
1         NJ, PA, IL, NY, CA, MA, DC

有什么建议可以做到吗?当然,对于所有此类情况,这都必须是动态的,这些状态仅是示例。

1 个答案:

答案 0 :(得分:1)

要将它们加入一起,您需要listagg:

select master_id, listagg(states, ', ') as states
from MyTable
group by master_id;

但是首先我们将它们拆分,然后使用不同的字符来删除这些重复项:

select master_id, listagg(distinct new_state, ', ') as states
from
(
  select master_id, TRIM(SPLIT_PART(states,',', 1)) as new_state
  from mytable
) x1
group by master_id

我想您要订购吗?好的,让我们这样做:

select master_id, 
       listagg(distinct new_state, ', ')
         within group (order by new_state) as states
from
(
  select master_id, TRIM(SPLIT_PART(states,',', 1)) as new_state
  from mytable
) x1
group by master_id