日期:2014-05-16 浏览次数:20507 次
原论坛贴子地址:点击打开链接 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