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

请问个SQL语句行变列的统计写法
例如如下表
客户名称                 材料名称                   重量
甲                                 A                               20
乙                                 B                               30
甲                                 B                               10
乙                                 A                               40
甲                                 C                               20
乙                                 A                               10

想出如下结果
客户名称               A                       B                     C
甲                           20                     10                   20
乙                           50                     30                   0

请问sql语句该如何写

------解决方案--------------------
create table A(客户名称 varchar(10),材料名称 varchar(10),重量 int)
insert A select '甲 ', 'A ',20
union all select '乙 ', 'B ',30
union all select '甲 ', 'B ',10
union all select '乙 ', 'A ',40
union all select '甲 ', 'C ',20
union all select '乙 ', 'A ',10

select 客户名称,A=isnull(sum(case 材料名称 when 'A ' then 重量 end),0),
B=isnull(sum(case 材料名称 when 'B ' then 重量 end),0),
C=isnull(sum(case 材料名称 when 'C ' then 重量 end),0) from A
group by 客户名称


客户名称 A B C
---------- ----------- ----------- -----------
甲 20 10 20
乙 50 30 0
------解决方案--------------------
declare @sql varchar(8000)
set @sql= ' '

select @sql=@sql+ ', '+材料名称+ '=sum(case 材料名称 when ' ' '+材料名称+ ' ' ' then 重量 else 0 end) '
from 表 group by 材料名称

set @sql= 'select 客户名称 '+@sql+ ' from 表 group by 客户名称 '

exec(@sql)
------解决方案--------------------
if object_id( 'pubs