根据相同的key合并值(行转列)

--删除测试表
--drop table test;
--创建测试表
create table test (fcode varchar(10),fname varchar(20));
--插入测试数据
insert into test(fcode, fname) values('1001', 'A1'),('1001', 'B1'),('1001', 'C1'),('1002', 'A2'),('1002', 'B2'),('1003', 'A3');

with temp1(id1, id2, fcode, fname) as (
  --数据结果1
  select row_number() over(partition by fcode order by fcode) id1, row_number() over(partition by fcode order by fcode) id2, fcode, fname from test
),
temp2(id1, id2, fcode, fname) as (
  --数据结果2
  select id1, id2, fcode, cast(fname as varchar(100)) from temp1 where id1 = 1 and id2 = 1
  union all
  select temp2.id1+1, temp2.id2, temp2.fcode, cast(temp1.fname||','||temp2.fname as varchar(100)) from  temp1, temp2
  where temp1.id2 = temp2.id1+1 and temp2.fcode = temp1.fcode
)
--数据结果3
select * from (
  select fcode, fname from temp2 where temp2.id1= (select max(id1) from temp1 where temp1.fcode = temp2.fcode)
) as t order by fcode

你可能感兴趣的:(key)