簡體   English   中英

SQL 服務器 Pivot 沒有列名

[英]SQL Server Pivot without column names

我有這張桌子:

庫存單位 品牌標識 條碼
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

我需要這種查詢結果格式:

庫存單位 品牌標識 條碼1 條碼2 條碼3 條碼4
1 1 123 987 852
1 2 951 753
2 1 926 364
2 2 854 256 351 157
2 3 976

條形碼應該是動態的,因為每個 SKU+BrandId 行都有未知的條形碼

這個概念是建立一個動態 pivot 查詢如下

 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

我強烈建議您不要將 go 向下動態查詢路由,因為它可能難以編碼,並且容易受到 SQL 注入的影響。

相反,只需在正常的條件聚合中硬編碼最大可能的Barcode列。

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; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM