1
我正面臨着一個問題,試圖在表上執行一個數據透視表。我想要的樣本如下所示。SQL Server 2008不支持彙總
ProductBarcode ProductID
-------------- ---------
1000 P1
1001 P1
1002 P2
1003 P3
1004 P4
1005 P4
現在我想將上表轉換爲如下所示。
ProductID Barcode1 Barcode2
--------- -------- --------
P1 1000 1001
P2 1002
P3 1003
P4 1004 1005
我試着用下面的查詢去解決它,但它並沒有給所要求的結果:
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]
現在這只是一個例子,在實際情況中,有數以百計的有多個條形碼的產品。
我甚至嘗試過使用下面的查詢,但我所得到的都是在兩個條碼列中爲空。
SELECT productID,[barcode1],[barcode2]
FROM
(SELECT barcode, productID
FROM products) as TableToBePivoted
PIVOT
(MAX(barcode)
FOR barcode IN ([barcode1], [barcode2])
) AS PivotedTable;
任何幫助將不勝感激。
感謝庫珀。我試過了你寫的查詢,我得到Barcode1列下的條形碼,但在Barcode2列下,它顯示了所有NULL。 – 2012-01-27 03:35:10
@Misbah - 我使用您的示例數據,爲我工作得很好。查詢除了數據透視操作符以外的所有內容時是否會得到預期的結果? – 2012-01-27 03:42:27
@Misbah Yanus - 我發佈了所有用於創建示例數據和查詢的SQL,用於創建預期結果 – 2012-01-27 03:46:42