Reputation: 13
I am facing a problem trying to perform a pivot on the table. A sample of what I want is as shown below.
ProductBarcode ProductID
-------------- ---------
1000 P1
1001 P1
1002 P2
1003 P3
1004 P4
1005 P4
Now I want to transform the above table into something as below.
ProductID Barcode1 Barcode2
--------- -------- --------
P1 1000 1001
P2 1002
P3 1003
P4 1004 1005
I was trying to work it out with the following query but it wasn't giving the required results:
SELECT
[r1].[productID],
[r1].[Productbarcode] as Barcode1,
[r2].[ProductBarcode] as Barcode2
FROM products as r1 right JOIN products as r2 on r1.[productID] = r2.[productID]
Now this is just an example and in actual case, there are hundreds of products which have multiple barcodes.
I have even tried using the following query but all I got was a null in both the barcode columns.
SELECT productID,[barcode1],[barcode2]
FROM
(SELECT barcode, productID
FROM products) as TableToBePivoted
PIVOT
(MAX(barcode)
FOR barcode IN ([barcode1], [barcode2])
) AS PivotedTable;
Any help would be greatly appreciated.
Upvotes: 1
Views: 2868
Reputation: 4998
No way to PIVOT without aggregating.
But here is how to get what you want, enter however many columns (barcodes) you want:
CREATE TABLE #table1(
ProductBarcode VARCHAR(10),
ProductID VARCHAR(10)
);
INSERT INTO #table1(ProductBarcode, ProductID)
VALUES
('1000' ,'P1'),
('1001' ,'P1'),
('1002' ,'P2'),
('1003' ,'P3'),
('1004' ,'P4'),
('1005' ,'P4');
WITH T AS(
SELECT 'Barcode' + RTRIM(LTRIM(STR( ROW_NUMBER() OVER(PARTITION BY ProductID ORDER BY ProductBarcode)))) AS BarcodeNum,
ProductBarcode,
ProductID
FROM #table1
)
SELECT * FROM T
PIVOT(MAX(ProductBarcode) FOR BarcodeNum IN([Barcode1], [Barcode2])) P
Results:
ProductID Barcode1 Barcode2
---------- ---------- ----------
P1 1000 1001
P2 1002 NULL
P3 1003 NULL
P4 1004 1005
Upvotes: 1