动态旋转主数据库和所有日期中的每个列

时间:2017-10-07 10:19:22

标签: sql tsql

我有表tbl_product_details喜欢:

create table tbl_product_details (productdate date, productname varchar(100), nav float , ncv float)



  insert into tbl_product_details 
    values('2017-10-04 00:00:00', 'UU8899', 10.23, 13.89),
    ('2017-10-05 00:00:00', 'UU8899', 12.23, 14.89)

和一个主表,其中存储所需的旋转列的名称,如。

 create table dynamiccols(id int , colname varchar(100))

 insert into dynamiccols
 values(1,'nav'),(1,'ncv')

我需要创建动态透视以显示所有日期列的透视数据以及dynamiccols中提到的每个列  表格如:

productname nav~~04-10-2017 nav~~05-10-2017 ncv~~04-10-2017 ncv~~05-10-2017
UU8899      10.23               12.23           13.89           14.89

我已经尝试过但不能让它在dynamiccols

中为每一列完成dyanmic
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName_header AS NVARCHAR(MAX)
DECLARE @ColumnName_pivot AS NVARCHAR(MAX) 
declare @kpiname varchar(100)='ncv' 

--Get distinct values of the PIVOT Column 
SELECT @ColumnName_header= ISNULL(@ColumnName_header + ',','') 
       + 'sum('+QUOTENAME(productdate) +') as ' ++QUOTENAME(@kpiname+'~~'+convert(varchar(11),productdate,105)),
       @ColumnName_pivot= ISNULL(@ColumnName_pivot + ',','') 
       + QUOTENAME(productdate)
FROM (SELECT DISTINCT productdate 
FROM tbl_product_details 
where productdate between '02-oct-2017' and '05-oct-2017') AS productdate


SET @DynamicPivotQuery = 
  N'    select * 
    from (  SELECT  productname ,' +  @ColumnName_header + '
    FROM tbl_product_details        
    PIVOT(sum('+@kpiname+') 
    FOR productdate IN (' + @ColumnName_pivot + ')) AS PVTTable        
    group by productname )  '+ char(97)


    print @DynamicPivotQuery
    exec(@DynamicPivotQuery)

0 个答案:

没有答案