Tuesday, October 28, 2014

Challenge with Pivoting data

Hopefully, this will help



Create Table Foo(ItemCode varchar(6), ItemDescription varchar(50), OrderQty decimal(12,6), BinLabel varchar(7), BinQty decimal(12,6));
Insert Foo(ItemCode, ItemDescription, OrderQty, BinLabel, BinQty) Values
('DR1124', 'D6 Series 24 OD 3/8 1 Neck', 50, 'B1A1904', 9),
('DR1124', 'D6 Series 24 OD 3/8 1 Neck', 50, 'M1D0703', 66),
('DR1124', 'D6 Series 24 OD 3/8 1 Neck', 50, 'S1K0603', 24),
('H21', 'Rubber Mallot', 75, 'X1X0712', 100),
('H21', 'Rubber Mallot', 75, 'T3B4567', 92);
Declare @SQL nvarchar(max);

;With cteRN As
(Select ItemCode, ItemDescription, BinLabel, BinQty,
Row_Number() Over(Partition By ItemCode Order By BinLabel) As rn
From Foo)
Select @SQL = (Select Cast(N'' As nvarchar(max)) + N', Max(Case When rn = ' + Cast(rn As nvarchar(5)) + N' Then BinLabel End) As BinLabel' + Cast(rn As nvarchar(5))
+ N', Max(Case When rn = ' + Cast(rn As nvarchar(5)) + N' Then BinQty End) As BinQty' + Cast(rn As nvarchar(5))
From (Select Distinct rn From cteRN) x
Order By rn
For XML Path(''))
Select @SQL = Stuff(@SQL, 1, 2, '');
--Select @SQL


Select @SQL = N'Select ItemCode, Max(ItemDescription) As ItemDescription, Max(OrderQty) As OrderQty,' + @SQL + N' From (Select ItemCode, ItemDescription, OrderQty, BinLabel, BinQty,
Row_Number() Over(Partition By ItemCode Order By BinLabel) As rn
From Foo) As x Group By ItemCode'
--select @SQL
Exec(@SQL);

-- Cleanup
go
Drop Table Foo;



Tom

No comments:

Post a Comment