问题描述
而且我想用期间列透视类别(可以增加/减少)列,并且还希望sold_amt、purchase_price、gross_profit作为行,请查看所需的图像,例如
提前致谢。
请找到
的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);
输出: