代码之家  ›  专栏  ›  技术社区  ›  user8834780

按列表聚合分组的问题

  •  2
  • user8834780  · 技术社区  · 7 年前

    在查询中 listagg() 我试图为split\u rep添加一个子句:存在 user_id 那已经 profile_type='Split' 用户id 不止一个 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 id 我需要进去 group by -然而,如果加上,那将给出错误的输出。不知道为什么listagg不支持窗口函数,但知道如何绕过它吗?

    样本数据:

    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
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Lukasz Szozda    7 年前

    你可以用 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;
    
        2
  •  1
  •   Tim Biegeleisen    7 年前

    select distinct group by . 每一个都可以做相似的事情,这取决于上下文。我用一个 CASE 下面的表达式来计算 split_rep_code 列,我还为 multi_rep_code 列。

    select
        r.user_id,
        listagg(ap.rep_code, ', ') within group (order by ap.bill_rate) as rep_code_list,
        case when sum(case when ap.profile_type = 'Split' then 1 else 0 end) > 0
             then 1 else 0 end as split_rep_code,
        case when min(ap.id) <> max(ap.id) then 1 else 0 end as multi_rep_code
    from representatives r
    inner join profiles ap
        on r.user_id = ap.user_id
    group by
        r.user_id;
    

    enter image description here

    Demo

    string_agg list_agg ,但原理是一样的。还要注意,Redshift不支持使用 DISTINCT 列表\u agg . 如果您真的需要这种行为,您可能必须先对子查询以删除重复项。