读书人

大伙帮帮忙!该如何解决

发布时间: 2012-02-29 16:44:10 作者: rapoo

大伙帮帮忙!
我想将
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)

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



DECLARE @s varchar(8000)
SET @s = ' '
SELECT @s = @s + N ', ' + QUOTENAME(namec) + N '=max(case when namec = ' + QUOTENAME(namec, ' ' ' ') + ' then price else null end) '
FROM(
SELECT DISTINCT namec FROM tb
)A
EXEC( '
select productid ' + @s + '
FROM tb
GROUP BY productid ')

读书人网 >SQL Server

热点推荐