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;
任何帮助将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有聚合就无法进行 PIVOT。
但这里是如何获得你想要的,输入你想要的任意数量的列(条形码):
结果:
No way to PIVOT without aggregating.
But here is how to get what you want, enter however many columns (barcodes) you want:
Results: