Sql dynamic rows rotation pivot column

 

Recently a friend have a demand: the product is "journal" book product lines turn to show the form of columns, while the need to associate the work order and work order list the main table, the display is, the work order number, date of operation, product names and the number, because the number of journals product, although static can be achieved, but not conducive to the follow-up to add content to think of how to show in a dynamic form, automatic splicing sql statement processing, the specific implementation process is as follows.

 Product information sheet required to field contents:

select ProductCode,Name  from ComProduct where ProductType ='20'

 

Ticket required content used:

select JobNo,ProductCode,Quantity  from WmsJobDtl 

 By searching for information, and finally complete dynamic SQL statements stitching, the specific stored procedure is as follows:

CREATE PROCEDURE 期刊核算汇总表

as 
begin


DECLARE @sql VARCHAR(8000)
DECLARE @COLUMN VARCHAR(8000)
 
SELECT @sql= ISNULL(@sql+',','')+ '['+ProductName+']'
    ,@COLUMN= ISNULL(@COLUMN,'')+', '+ProductName 


FROM (select wj.JobNo ,wj.StockDate, a.ProductName ,sum(wjd.Quantity) as TQty   from 
(select ProductCode,  Name as ProductName  
from ComProduct   where  ProductType ='20' ) as a 
inner  join  WmsJobDtl wjd on a.ProductCode = wjd.ProductCode
inner join WmsJob  wj on wj.JobNo = wjd.JobNo
where wj.Status = 'X'  
group by wj.JobNo ,wj.StockDate, a.ProductName) as cc 
GROUP BY ProductName           
 
SET @sql=' select  *  from
(select wj.JobNo ,wj.StockDate, a.ProductName ,sum(wjd.Quantity) as TQty   from 
(select ProductCode,  Name as ProductName  
from ComProduct   where  ProductType =''20'' ) as a 
inner  join  WmsJobDtl wjd on a.ProductCode = wjd.ProductCode
inner join WmsJob  wj on wj.JobNo = wjd.JobNo
where wj.Status = ''X''  
group by wj.JobNo ,wj.StockDate, a.ProductName
) as  dddd  pivot (max(TQty) for ProductName in ('+@sql+'))a'
 
exec   (@sql)

end

 

Unfortunately, there is no problem worth solving NULL, if any can be resolved, welcome message, thank you very much.

 

Guess you like

Origin www.cnblogs.com/sbjl/p/11432358.html