水滴石穿

渴望成为高手--Amy.Qiu
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

SQL行列轉換

Posted on 2007-05-23 15:58  AmyQiu  阅读(652)  评论(0编辑  收藏  举报

create table row_to_column
(
 code int,
 name varchar(10),
 value int
)
insert into row_to_column
 select 1,'name1',20
 union
 select 2,'name1',30
 union
 select 1,'name2',30
 union
 select 2,'name2',30
 union
 select 3,'name3',20
 union
 select 1,'name3',20
 union
 select 2,'name3',30

select * from row_to_column
select distinct name from row_to_column

--select code,sum(case when name='name1' then value else 0 end) as name1,
-- sum(case when name='name2' then value else 0 end) as name2,
-- sum(case when name='name3' then value else 0 end) as name3
-- from row_to_column
-- group by code

declare @sql varchar(8000)
set @sql=''
SELECT @sql = @sql + N',' + quotename(name) + N'= SUM(CASE name WHEN ' + QUOTENAME(name, '''') + ' THEN value ELSE 0 END)'
 FROM(
  SELECT DISTINCT name FROM row_to_column
 )A
--print @sql
set @sql =substring(@sql,2,len(@sql))
--print @sql
EXEC('
  select code,'+ @sql + '
  FROM row_to_column
  GROUP BY code')