日期:2014-05-17  浏览次数:20732 次

SQL行转列功能操作
我的数据如下:
天使宝贝系列 201105 9000
   天使宝贝系列 201106 8000
  爱恋一生系列 201105 6000
  爱恋一生系列 201106 500
    简约风尚系列 201105 5000
  简约风尚系列 201106 600
  浪漫田园系列 201105 600
   浪漫田园系列 201106 600
要求查询出来结果为:
                        201105   201106  201107 ...
天使宝贝系列 9000      8000
  爱恋一生系列 6000      500
    简约风尚系列 5000      600
  浪漫田园系列 600       600

------解决方案--------------------
见精华 很多
------解决方案--------------------

if object_id('tempdb.dbo.#t') is not null drop table #t
create table #t (category varchar(12),code varchar(12),qty int)
insert into #t
select '天使宝贝系列',201105,9000 union all
select '天使宝贝系列',201106,8000 union all
select '爱恋一生系列',201105,6000 union all
select '爱恋一生系列',201106,500 union all
select '简约风尚系列',201105,5000 union all
select '简约风尚系列',201106,600 union all
select '浪漫田园系列',201105,600 union all
select '浪漫田园系列',201106,600

select * from #t
declare @sql varchar(8000)
select @sql = isnull(@sql + ',' , '') + '['+code+']' from #T group by code
exec ('select * from (select * from #T) a pivot (max(qty) for code in (' + @sql + ')) b')

category 201105 201106
爱恋一生系列 6000 500
简约风尚系列 5000 600
浪漫田园系列 600 600
天使宝贝系列 9000 8000



------解决方案--------------------

create table #tb 
(string nvarchar(50),date nvarchar(10),amt int)
insert #tb
select '天使宝贝系列','201105', 9000 union all
select '天使宝贝系列','201106', 8000 union all
select '爱恋一生系列','201105', 6000 union all
select '爱恋一生系列','201106', 500 union all
select '简约风尚系列','201105', 5000 union all
select '简约风尚系列','201106', 600 union all
select '浪漫田园系列','201105', 600 union all
select '浪漫田园系列','201107', 545 union all
select '简约风尚系列','201107', 777 union all
select '简约风尚系列','201108', 888 union all
select '浪漫田园系列','201108', 999 union all
select '浪漫田园系列','201107', 654

declare @sql as nvarchar(4000)
set @sql='select string'
select @sql=@sql+',sum(case when date='''+date+''' then amt else 0 end) as '''+date+''''
       from (select distinct date from #