SQL 按复合组连接行

SQL Concatenate Rows by Composite Group

我需要使用两个分组值根据该行属于哪个组将行值连接到一个列中。

TBL1

    cat1 cat2 cat3 value
    ---- ---- ---- -----
    1    1    lvl1 100
    1    2    lvl2 abc 
    1    3    lvl2 cba 
    2    1    lvl1 200 
    2    2    lvl2 abb
    3    1    lvl1 100
    3    2    lvl2 bbc
    3    3    lvl2 acc
    3    4    lvl1 400
    3    5    lvl2 acc 
    4    1    lvl1 300
    4    2    lvl2 aab
    ...

TBL2

    cat1 cat2 value
    ---- ---- ---------
    1    100  abc, cba
    2    200  abb
    3    100  bbc, aac
    3    400  aac
    4    300  aab
    ...

这是使用静态 DB2 SQL。实际table有上千条记录。

至少某些版本的 DB2 支持 listagg()。所以棘手的部分是识别组。您可以通过累计计算值为数字的行数来执行此操作。结果查询是这样的:

select cat1,
       max(case when value >= '0' and value <= '999' then value end) as cat2,
       listagg(case when not value >= '0' and value <= '999' then value end, ', ') within group (order by cat2) as value
from (select t.*,
             sum(case when value >= '0' and value <= '999' then 1 else 0 end) over (order by cat1, cat2) as grp
      from t
     ) t
group by cat1, grp;

在 DB2 中检查数字可能很棘手。上面使用了足以满足您的示例数据的简单逻辑。