- 爱易网页
 
                        - 
                            MSSQL教程
 
                        - 求SQL。解决办法 
 
                         
                    
                    
                    日期:2014-05-18  浏览次数:20584 次 
                    
                        
                         求SQL。。。
商品销售情况表 
 table1 
 销售员         品名            数量 
 张                     电视               4 
 张                     冰箱               1 
 王                     电视               3 
 李                     空调               2 
 王                     洗衣机         1 
 张                     空调               3 
 张                     电视               1 
 ................. 
 要得到一下表 
 个人销售报告表 
 table2 
 售货员         电视         冰箱         空调      洗衣机            总件数 
 张                           5                  1               0                        0                        6 
 王                           3                  0               0                        0                        3 
 李                           0                  0               2                        0                        2
------解决方案--------------------
create table T(销售员 char(7), 品名 varchar(10), 数量 int) 
 insert T select  'zhang ',       '电视 ',        4 
 union all select  'zhang ',       '冰箱 ',      1 
 union all select  'wang ',       '电视 ',        3 
 union all select  'li ',       '空调 ',        2 
 union all select  'wang ',       '洗衣机 ',        1 
 union all select  'zhang ',       '空调 ',      3 
 union all select  'zhang ',       '电视 ',        1 
  
  
 declare @sql varchar(4000) 
 set @sql= 'select 销售员, ' 
 select @sql=@sql+quotename(品名)+ '=sum(case when 品名= ' ' '+品名+ ' ' ' then [数量] end), ' from T 
 group by 品名 
 select @sql=left(@sql, len(@sql)-1), @sql=@sql+ ' from T group by 销售员  ' 
  
 exec(@sql)
------解决方案--------------------
我写完整点 
 create table table1(销售员 char(7), 品名 varchar(10), 数量 int) 
 insert table1 select  '张 ',       '电视 ',        4 
 union all select  '张 ',       '冰箱 ',      1 
 union all select  '王 ',       '电视 ',        3 
 union all select  '李 ',       '空调 ',        2 
 union all select  '王 ',       '洗衣机 ',        1 
 union all select  '张 ',       '空调 ',      3 
 union all select  '张 ',       '电视 ',        1 
  
 select * from table1 
  
 declare @sql varchar(4000) 
 set @sql= 'select 销售员, ' 
 select @sql=@sql+quotename(品名)+ '=isnull(sum(case when 品名= ' ' '+品名+ ' ' ' then [数量] end),0), ' from table1 
 group by 品名 
 select @sql=@sql+ 'sum(数量) 总件数 from table1 group by 销售员 order by 销售员 desc ' 
 print @sql 
 exec(@sql)