简体   繁体   中英

SQL Server Pivot without column names

I have this table:

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

I need this query result format:

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

The barcode should be dynamic because there is unkown Barcodes for every SKU+BrandId row

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

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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM