行的内容变换到列显示,并且添加行求和,列求和

来源:互联网 发布:网络教育全托 编辑:程序博客网 时间:2024/05/21 23:37

StoreCode         GoodsCode           Size                 Color           Num  
      s1                     g1                         165                     01               2  
      s1                     g2                         170                     01               1  
      s1                     g1                         170                     02               3  
      s2                     g1                         165                     01               4  
      s2                     g2                         170                     01               5  
  ......  
   
  显示结果如下:  
  GoodsCode             Size             Color             s1             s2             ColSum  
        g1                       165               01                 2               4                 6  
        g1                       170               02                 3               0                 3  
        g2                       170               01                 1               5                 6  
                                                                          6               9                 15  
   
  也有可能这样显示  
  GoodsCode                 s1             s2             ColSum  
        g1                         5               4                 9  
        g2                         1               5                 6   
       null                        6               9                 15  

解答

 --插入数据   
  Insert   TEST   
  
Select   's1','g1','165','01','2'   
  
Union   All   
  
Select   's1','g2','170','01','1'   
  
Union   All   
  
Select   's1','g1','170','02','3'   
  
Union   All   
  
Select   's2','g1','165','01','4'   
  
Union   All   
  
Select   's2','g2','170','01','5'   
  
Union   All   
  
Select   's3','g2','170','01','5' 
  
Union   All   
  
Select   's4','g3','170','01','5' 
  
--测试   
  Declare   @S Varchar(1000)   
  
Set   @S='Select   GoodsCode'   
  
Select   @S=@S+','+'SUM(Case   StoreCode   When   '''+StoreCode+'''   Then   Num   Else   0   End)   As   '+StoreCode   
  
from   (Select   Distinct   StoreCode   from   TEST   )   A   Order   by   StoreCode   
  
Set   @S=@S+'   ,SUM(Num)   As   ColSum   from   TEST   Group   By   GoodsCode   With   Rollup   '   
print @s
  
EXEC(@S)   
  
--删除测试环境   
  Drop   Table   TEST   
  
--结果   
  /*   
  GoodsCode s1 s2 ColSum   
  g1 5 4 9   
  g2 1 5 6   
  NULL 6 9 15   
  
*/
   
详见http://topic.csdn.net/t/20050619/21/4092792.html
原创粉丝点击