关于oracle和db2中的纵表转横表的例子

在数据库开发的过程中,经常会遇到把纵表的数据转换为横表展示出来。今天我就把经常遇到的实现的方法总结出来,还请大家指点错误啊。或者有更好的方法,也可以让我学习学习。
---以下脚本是在db2中实现的
第一个:纵表转横表的"SQL"示例
纵表结构: TEST_vip
acct_month 卡级别 数量
201201 钻卡 1
201201 金卡 2
201201 银卡 3

转换后显示如下
acct_month 钻卡数量 金卡数量 银卡数量
201201 1 2 3

实现思路为先将表中的数据构造成需要展示的列数,再在最外层将此值全部累加即可。

实现的sql为:
select acct_month,
sum(zk_count),
sum(jk_count),
sum(yk_count)
from (select acct_month,
case when card_level = '钻卡' then card_count end as zk_count,
case when card_level = '金卡' then card_count end as jk_count,
case when card_level = '银卡' then card_count end as yk_count
from TEST_vip
) group by acct_month;


第二个:
表结构如下:
表1 表2
字段1 字段2 字段3 字段4
A 1 A 1,2,3
A 2 B 5,6
A 3 C 7,8,9
B 5
B 6
C 7
C 8
C 9

转换要求:
使用sql实现,汇总表1字段1,字段2值用逗号隔开写入表2字段4


实现的sql为:
create table test_lyq(f1 varchar(3), f2 integer);

insert into test_lyq
values
('A',1),
('A',2),
('A',3),
('B',5),
('B',6),
('C',7),
('C',8),
('C',9);

WITH TMP(c1,c2,c3) as
(
select f1,f2,char(f2) from test_lyq
where (f1,f2) in (select f1,min(f2) from test_lyq group by f1)

union all

select t1.c1,t1.c2+1,rtrim(t1.c3)||','||rtrim(char(t2.f2)) from tmp t1 , test_lyq t2
where t1.c1 = t2.f1 and t1.c2+1 = t2.f2
)
select c1,c3 from tmp where (c1,c2) in (select f1,max(f2) from test_lyq group by f1);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值