首页 > 解决方案 > 使用列表聚合的 group by 问题

问题描述

在一个查询中,listagg()我试图为 split_rep:existence of user_idthat has添加一个子句profile_type='Split',而对于 multi_rep:existence of user_idwith more than one ap.id

简化查询(其中 -- 是我想要做的):

select distinct r.user_id,
listagg(distinct ap.rep_code, ', ') within group (order by ap.bill_rate) as rep_code_list
--,case when max(ap.profile_type) over (partition by r.user_id)='Split' then 1 else 0 end has_split_rep_code
--,case when count(ap.id) over (partition by r.user_id)>1 then 1 else 0 end has_multi_rep_code 
from representatives r
join profiles ap on r.user_id=ap.user_id
group by r.user_id

这会引发一个需要出现profile_type的错误- 但是如果添加,则会给出错误的输出。不知道为什么 listagg 不支持窗口函数,但知道如何绕过它吗?idgroup by

样本数据:

user_id   id   profile_type   rep_code
A         A    Self           AAA
A         B    Self           AAB
B         C    Self           AAC
C         D    Self           AAD
C         E    Split          AAE
D         F    Split          AAF

期望的输出:

user_id   rep_code    split_rep_code   multi_rep_code
A         AAA, AAB    0                1
B         AAC         0                0
C         AAD, AAE    1                1
D         AAF         1                0

标签: sqlamazon-redshift

解决方案


你可以使用OVER

select distinct r.user_id,
  listagg(distinct ap.rep_code, ', ') within group (order by ap.bill_rate)
   over(partition by ap.user_id) as rep_code_list
  -- rest of cols
from representatives r
join profiles ap on r.user_id=ap.user_id;

推荐阅读