行列转换问题案例回答

 原论坛贴子地址:点击打开链接  
  
http://topic.csdn.net/u/20120817/14/2b37210c-e7cb-4713-bca3-97eb1f600ca7.html?seed=1450377381&r=79434916#r_79434916     
  
  
   
 /********************************************************************************               
 *主题: SQl 2008/2005 论坛问题解答               
 *说明:本文是个人学习的一些笔记和个人愚见                
 *      有很多地方你可能觉得有异议,欢迎一起讨论                
                
 *作者:Stephenzhou(阿蒙)                
 *日期: 2012.08.17          
 *Mail:szstephenzhou@163.com                
 *另外:转载请著名出处。                
**********************************************************************************/   

 
create table tb (col1 varchar(20),col2 varchar(20))
insert tb
select 'A','ddd' union all
select 'B','asdf' union all
select 'C','dsdf' union all
select 'D','eee' union all
select 'E','geas' union all
select 'F','2' union all
select 'G','5d' union all
select 'H','sad' union all
select 'I','ww' union all
select 'J','23' union all
select 'K','asdfw'  

 
declare @sql varchar(max)
declare @qls varchar(8000)
select @sql ='select ';
 select @sql+=' max(case col1 when '''+col1+''' then col2 else null end)['+col1+'] ,'
 from (select distinct col1 from tb)as a
set @sql = @sql + 'from tb  '
set @sql=substring(@sql,0,charindex('from',@sql)-1)+substring(@sql,charindex('from',@sql),LEN(@sql))
print @sql
exec (@sql)
 
  /*
  
  A                    B                    C                    D                    E                    F                    G                    H                    I                    J                    K
-------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- --------------------
ddd                  asdf                 dsdf                 eee                  geas                 2                    5d                   sad                  ww                   23                   asdfw
 

(1 行受影响)

  */
 
  
 --or

 

select
MAX(case col1 when 'A' then col2 else null end ) as 'A',
MAX(case col1 when 'B' then col2 else null end ) as 'B',
MAX(case col1 when 'C' then col2 else null end ) as 'C',
MAX(case col1 when 'D' then col2 else null end ) as 'D'
..
...
..
  from tb


 *作者:Stephenzhou(阿蒙)     
 *日期: 2012.08.17

 *Mail:szstephenzhou@163.com     
 *另外:转载请著名出处。
 *博客地址:http://blog.csdn.net/szstephenzhou

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值