SQL使用LISTAGG()连接10个组中的一列

时间:2016-11-28 13:22:54

标签: sql oracle concatenation listagg

我需要帮助编写一个查询,该查询可以连接10个组中的一个列。

示例:

id1 | string1
id1 | string2
id1 | string3
...
id1 | string 1000

由于SQL不允许使用过大的连接字符串,我希望一次可以组成10个字符串,以便我得到:

id1 | string1,string2,...,string10
id1 | string11,string12,...,string20

由于

1 个答案:

答案 0 :(得分:1)

select      id,listagg (str,',') within group (order by str)

from       (select      id,str,row_number () over (partition by id order by str) - 1    as rn
            from        t
            ) 

group by    id,floor (rn / 10)
;

或者如果您不关心订单 -

select      id,listagg (str,',') within group (order by null)

from       (select      id,str,rownum - 1 as rn
            from        t
            ) 

group by    id,floor (rn / 10)
;

示例

create table t
as
select          'id'    || to_char(ceil(level/100))     as id
                ,'str'  || lpad(to_char(level),4,'0')   as str
from            dual
connect by      level <= 1000
;