日期:2014-05-18  浏览次数:20383 次

大伙帮帮忙!
我想将      
productid             namec     price  
02         江西               12
04       西南                   15
04       江西                   20
05       丹麦                   30
05       通化                     40
07       通化                     20
...
动态的转化为
productid               江西       西南         丹麦     通化
02                 12
04                 20           15
                                         
05                                             30           40        
07                                                           20                      
      就是纵向转化为横向       但是纵向的namec   也要换过来            


------解决方案--------------------
select productid,
max(case when namec = '江西 ' then price else null end) as 江西,
max(case when namec = '西南 ' then price else null end) as 西南,
max(case when namec = '丹麦 ' then price else null end) as 丹麦,
max(case when namec = '通化 ' then price else null end) as 通化
from tb group by productid

------解决方案--------------------
declare @sql varchar(8000)
set @sql= ' '

select @sql= ',[ '+namec+ ']=max(case namec when ' ' '+namec+ ' ' ' then price end) ' from 表 group by namec

set @sql= 'select productid '+@sql+ ' from 表 group by productid '

exec(@sql)
------解决方案--------------------
create table testaaa(productid varchar(10), namec varchar(100), price int)
insert testaaa select '02 ' , '江西 ', 12
union all select '04 ', '西南 ', 15
union all select '04 ', '江西 ', 20
union all select '05 ', '丹麦 ', 30
union all select '05 ', '通化 ',40
union all select '07 ', '通化 ', 20

declare @s varchar(1000)
set @s= ' '
select @s=@s+ 'sum(case when namec = ' ' '+namec + ' ' ' then price else 0 end) '+ [namec] + ', ' from testaaa group by namec
select @s=left(@s,len(@s)-1)
select @s

set @s= 'select productid, '+@s + ' from testaaa group by productid '
exec(@s)

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