根据相同的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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值