我的数据如下:
天使宝贝系列 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

解决方案 »

  1.   

    declare @sql varchar(8000)
    set @sql = 'select name '
    select @sql = @sql + ' , max(case date when ''' + date + ''' then [value] else 0 end) [' + date + ']'
    from (select distinct date from tb) as a
    set @sql = @sql + ' from tb group by name'
    exec(@sql) 
      

  2.   


    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,600select * 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
      

  3.   


    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', 654declare @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 #tb) as T
    set @sql=@sql+' from #tb group by string'
    exec(@sql)