日期:2014-05-18 浏览次数:20722 次
declare @sql nvarchar(1000) set @sql = 'select facid [机型] ' select @sql = @sql+ ','''+convert(varchar(100),machineid)+ '''= sum(case machineid when '''+convert(varchar(100),machineid)+ ''' then num else 0 end) ' from (select distinct machineid from facmachine) dd set @sql = @sql+ ', sum(num) as [总计] from facmachine group by facid ' exec (@sql)
------解决方案--------------------
create   table   facmachine   
( 
    facid   int, 
    machineid   int, 
    num   int 
) 
insert   into   facmachine   select   '1000 ', '100 ',10   union   all 
    select   '1000 ', '200 ',10   union   all 
    select   '2000 ', '100 ',100   union   all 
    select   '3000 ',   '400 ',100 
declare   @sql   nvarchar(1000) 
set @sql = 'select facid [机型]' 
select @sql = @sql+ ', sum(case machineid when ''' + cast(machineid as varchar) + ''' then num else 0 end) ['+cast(machineid as varchar)+']'
from (select distinct machineid from facmachine) dd 
set @sql = @sql+ ', sum(num) as [总计] from facmachine group by facid ' 
exec   (@sql) 
/*
机型          100         200         400         总计          
----------- ----------- ----------- ----------- ----------- 
1000        10          10          0           20
2000        100         0           0           100
3000        0           0           100         100
*/
------解决方案--------------------
create   table   facmachine   
( 
    facid   int   , 
    machineid   int, 
    num   int 
) 
insert   into   facmachine   select   1000,100,10   union   all 
    select   '1000 ', '200 ',10   union   all 
    select   '2000 ', '100 ',100   union   all 
    select   '3000 ',   '400 ',100 
select   *   from   facmachine   
declare   @sql   nvarchar(1000) 
set   @sql     =   'select   facid       [机型] ' 
select   @sql   =   @sql+   ', ['+cast(machineid as char(20))+ 
']=   sum(case   machineid   when   '+cast([machineid] as varchar(20))+
 '   then   num   else   0   end) '  
 from   (select   distinct   machineid   from   facmachine)   dd 
  
set   @sql   =   @sql+ ',   sum(num)   as   [总计]   from   facmachine   group   by   facid   ' 
exec   (@sql) 
/*
机型          100                  200                  400                  总计          
----------- -------------------- -------------------- -------------------- ----------- 
1000        10                   10                   0                    20
2000        100                  0                    0                    100
3000        0                    0                    100                  100
*/
drop   table   facmachine