动态语句编写行转列的SQL

动态语句编写行转列的SQL,可以防止一些列的值是未知的情况下可以使用动态语句来将行转换为列: 

举例如下:

表名:TB1
SEQ ID   NAME
----------------
1   1A     AA
2   2B     BB
3   3C     CC
需要改为

1A   2B   3C
--------------
AA   BB   CC


create table TB1
(SEQ  number,
ID    varchar2(10),
NAME  varchar2(10))

select t.* from tb1 t

select distinct A.* from(
select (case when id='1A' then name else (select name from TB1 where id='1A')  end) "1A"
      ,(case when id='2B' then name else (select name from TB1 where id='2B')  end) "2B"
      ,(case when id='3C' then name else (select name from TB1 where id='3C')  end) "3C"
 from TB1
 )A
--写成动态语句的存储过程
create or replace procedure testdm(mycursor out  sys_refcursor) is
m_sql  varchar2(4000);
m_sql1 varchar2(4000);
c sys_refcursor;
temp varchar2(10);
begin
m_sql:=' select distinct * from( select ';
OPEN c for
select distinct id from tb1;
loop
fetch c into temp;
EXIT WHEN (c%NOTFOUND);
m_sql1:=m_sql1||',(case when ID='''||temp||''' then name else (select name from TB1 where id= ''' ||temp||''' ) end) "'||temp||'" ';
END LOOP;
m_sql1:=LTRIM(m_sql1,',');
m_sql:=m_sql||m_sql1||' from TB1 ) A';
open mycursor for
m_sql;
end testdm;

 

下面的SQL语句是oracle群里一个朋友的写法,记录下来供大家分享:
SQL2000的写法:
create table aa([Name] varchar(10),[Subject] varchar(20),Result int);
insert into aa([Name],[Subject],Result)
select '张三','语文',80 union all
select '张三','数学',90 union all
select '张三','物理',85 union all
select '李四','语文',85 union all
select '李四','数学',92 union all
select '李四','物理',82

declare @sql varchar(4000)
set @sql = 'select Name'
select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result end) ['+Subject+']' from (select distinct Subject from aa) as a
select @sql = @sql+' from aa group by name'
select @sql
exec(@sql)


drop table aa

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值