数字列上的动态多个 PIVOT

问题描述

我有一个表,其中包含类似的数据

enter image description here

而且我想用期间列透视类别(可以增加/减少)列,并且还希望sold_amt、purchase_price、gross_profit作为行,请查看所需的图像,例如

enter image description here

提前致谢。

请找到

的create和insert语句
CREATE TABLE temp_key_category (
category_code varchar(30),sold_amt DECIMAL(12,4),purchase_price DECIMAL(12,gross_profit DECIMAL(12,item_qty DECIMAL(12,2),period VARCHAR(100),salesperson_code VARCHAR(100),salesperson_name VARCHAR(100)
);

插入-

INSERT INTO temp_key_category values('BICEGO',17433.0000,16740.0000,3.9752,8.00,'Rolling 12 Periods',166,'Ben Ehrmann')
INSERT INTO temp_key_category values('BRIDAL',1533.0000,1680.0000,3.0,5.00,116,'Anthony')
INSERT INTO temp_key_category values('BRIDAL',5533.0000,1590.0000,3.5,'Current Period','Anthony')
INSERT INTO temp_key_category values('LOOSE DIAMONDS',69131.0000,39117.4000,43.4155,'Anthony')  
INSERT INTO temp_key_category values('LOOSE DIAMONDS',8131.0000,3517.4000,43.458,'Anthony')  
INSERT INTO temp_key_category values('YURMAN',7131.0000,'Kiley')    


select * from temp_key_category

解决方法

这是您的动态支点:

 DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
    
SET @cols = STUFF((SELECT distinct ',' + quotename(concat(category_code,'_',period))
            FROM temp_key_category 
            FOR XML PATH(''),TYPE
            ).value('.','NVARCHAR(MAX)'),1,'')
               
            
       
set @query = 'select salesperson_code,' + @cols + ' from 
            (
  select c.salesperson_code,SalesOrPurchase,concat(category_code,''_'',period)cetegoryperiod
from temp_key_category
cross apply
(
  select concat(salesperson_code,''sold_amt''),sold_amt union all
  select concat(salesperson_code,''purchase_price''),purchase_price 
  
) c (salesperson_code,SalesOrPurchase)

) x
            pivot 
            (
              sum(salesorpurchase)
  for cetegoryperiod in (' + @cols + ')

            ) p 
            group by salesperson_code,' + @cols 


execute(@query);

输出:

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...