'Dynamic Pivot without aggregate in SQL Server
I have 3 columns in a table and I want to create a dynamic Pivot query.
The SKU and BrandId columns is the "Distinct" side, and the Barcode column should expand side.
Note: The Barcode column should be dynamic because there is unknown Barcodes for every SKU+BrandId.
| SKU | BrandId | Barcode |
|---|---|---|
| 1 | 1 | 123 |
| 1 | 1 | 987 |
| 1 | 1 | 852 |
| 1 | 2 | 951 |
| 1 | 2 | 753 |
| 2 | 1 | 926 |
| 2 | 1 | 364 |
| 2 | 2 | 854 |
| 2 | 2 | 256 |
| 2 | 2 | 351 |
| 2 | 2 | 157 |
| 2 | 3 | 976 |
Expecting this result:
| SKU | BrandId | Barcode1 | Barcode2 | Barcode3 | Barcode4 |
|---|---|---|---|---|---|
| 1 | 1 | 123 | 987 | 852 | |
| 1 | 2 | 951 | 753 | ||
| 2 | 1 | 926 | 364 | ||
| 2 | 2 | 854 | 256 | 351 | 157 |
| 2 | 3 | 976 |
Solution 1:[1]
the concept is to build a dynamic pivot query as follow
CREATE TABLE #t (sku nvarchar(5), brandid nvarchar(5), barcode nvarchar(50) )
truncate table #t
INSERT INTO #t VALUES
(1,1,150),
(1,1,140),
(1,1,111),
(1,2,1234),
(1,2,145),
(2,1,345),
(2,1,532),
(2,2,875),
(2,2,1237),
(3,1,566)
select *,'Barcode'+CONVERT (nvarchar(50),ROW_NUMBER()over(partition by sku, brandid order by sku)) rn from #t
DECLARE @colName AS NVARCHAR(MAX), @pivotQ AS NVARCHAR(max)
SELECT @colName = ISNULL(@colName + ',', '') + QUOTENAME(rn)
FROM (select DISTINCT 'Barcode'+CONVERT (nvarchar(50),ROW_NUMBER()over(partition by sku, brandid order by sku)) rn from #t
) AS Labels ORDER BY rn
SET @pivotQ = N'
SELECT sku, brandid, '+@colName+'
FROM
(
SELECT sku, brandid , barcode , ''Barcode''+CONVERT (nvarchar(50),ROW_NUMBER()over(partition by sku, brandid order by sku)) rn
FROM #t
) AS SourceTable
PIVOT
(
MAX(barcode)
FOR rn IN ('+@colName+')
) AS PivotTable;
'
EXECUTE sp_executesql @pivotQ
Solution 2:[2]
I strongly suggest you do not go down the dynamic query route, as it can be difficult to code, and vulnerable to SQL injection.
Instead just hard-code the maximum possible Barcode columns in a normal conditional aggregation.
SELECT
t.Sku,
t.BrandId,
Barcode1 = MAX(CASE WHEN t.rn = 1 THEN t.Barcode END),
Barcode2 = MAX(CASE WHEN t.rn = 2 THEN t.Barcode END),
Barcode3 = MAX(CASE WHEN t.rn = 3 THEN t.Barcode END),
Barcode4 = MAX(CASE WHEN t.rn = 4 THEN t.Barcode END),
Barcode5 = MAX(CASE WHEN t.rn = 5 THEN t.Barcode END),
Barcode6 = MAX(CASE WHEN t.rn = 6 THEN t.Barcode END),
Barcode7 = MAX(CASE WHEN t.rn = 7 THEN t.Barcode END),
Barcode8 = MAX(CASE WHEN t.rn = 8 THEN t.Barcode END),
Barcode9 = MAX(CASE WHEN t.rn = 9 THEN t.Barcode END),
Barcode10 = MAX(CASE WHEN t.rn = 10 THEN t.Barcode END)
FROM
(
SELECT *,
rn = ROW_NUMBER() OVER (PARTITION BY t.Sku, t.BrandId ORDER BY t.Barcode)
FROM YourTable t
) t
GROUP BY
t.Sku,
t.BrandId;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohammad SerajAldin |
| Solution 2 | Charlieface |
