技不如人

Welcome to Rickel's blog.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

SQL - Row to Columns

Posted on 2005-01-17 09:48  Rickel  阅读(1175)  评论(0编辑  收藏  举报
在以前写过的项目中SQL中经常遇到行变列的处理
大多使用的方法是先捞出数据在进行循环得到结果
刚刚发现一个好方法,可以直接用SQL语句执行达到这个效果
不用进行循环。
--测试数据
create table tb1(tid int,tvalue varchar(20))
insert tb1 select 1,'2004Q1' union all select 1,'2004Q2' union all select 1,'2004Q3'
union all select 1,'2004Q4'  union all select 1,'2005Q1'  union all select 2,'2006Q3'
union all select 2,'2006Q4' union all select 3,'2008Q2' union all select 3,'2008Q3'
--生成结果
declare @s varchar(100set @s=''
select @s=@s+',['+tvalue+']=''''' from tb1 where tid=1
exec('select distinct tid'+@s+' from tb1 where tid=1')
drop table tb1