可以用递归实现:
with table1 ( c1 ) as (
values (1),(2) )
,table2 ( c1,c2 ) as (
values(1,11),
(1,12),
(1,13),
(2,11),
(2,12) )
, temp1 ( c1,c2,c3 ) as ( select t1.c1,trim(char(t1.c2)),row_number() over ( partition by t1.c1 order by t1.c2 )
from table1 t2, table2 t1 where t1.c1=t2.c1 )
, temp2 ( c1 ,c2 ,c3 ) as (
select c1,cast(c2 as varchar(20)),c3 from temp1 where c3 = 1
union all
select a.c1,concat(concat(b.c2,','),a.c2),a.c3 from temp1 a, temp2 b
where a.c1 = b.c1 and a.c3 = b.c3 + 1 )
select c1,c2 from temp2 where (c1,c3) in ( select c1,max(c3) from temp2 group by c1 )
|