当前位置: 代码迷 >> Sql Server >> 请教个SQL语句行变列的统计写法
  详细解决方案

请教个SQL语句行变列的统计写法

热度:41   发布时间:2016-04-27 16:33:59.0
请问个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 @[email protected]+ ', '+材料名称+ '=sum(case 材料名称 when ' ' '+材料名称+ ' ' ' then 重量 else 0 end) '
from 表 group by 材料名称

set @sql= 'select 客户名称 '[email protected]+ ' from 表 group by 客户名称 '

exec(@sql)
------解决方案--------------------
if object_id( 'pubs..tb ') is not null
  相关解决方案