无聚合的SQL Server 2008 Pivot
我在试着在桌子上做旋转时遇到了一个问题。我想要的样本如下所示无聚合的SQL Server 2008 Pivot,sql,sql-server,sql-server-2008,pivot,aggregation,Sql,Sql Server,Sql Server 2008,Pivot,Aggregation,我在试着在桌子上做旋转时遇到了一个问题。我想要的样本如下所示 ProductBarcode ProductID -------------- --------- 1000 P1 1001 P1 1002 P2 1003 P3 1004 P4 1005 P4 现在我想把上面的表转换成如下的内容 ProductID Barco
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;
如果有任何帮助,我们将不胜感激。如果不进行聚合,就无法实现重点 但以下是如何获取所需内容,输入所需的列数(条形码):
CREATE TABLE #table1(
ProductBarcode VARCHAR(10),
ProductID VARCHAR(10)
);
INSERT INTO #table1(ProductBarcode, ProductID)
VALUES
('1000' ,'P1'),
('1001' ,'P1'),
('1002' ,'P2'),
('1003' ,'P3'),
('1004' ,'P4'),
('1005' ,'P4');
WITH T AS(
SELECT 'Barcode' + RTRIM(LTRIM(STR( ROW_NUMBER() OVER(PARTITION BY ProductID ORDER BY ProductBarcode)))) AS BarcodeNum,
ProductBarcode,
ProductID
FROM #table1
)
SELECT * FROM T
PIVOT(MAX(ProductBarcode) FOR BarcodeNum IN([Barcode1], [Barcode2])) P
结果:
ProductID Barcode1 Barcode2
---------- ---------- ----------
P1 1000 1001
P2 1002 NULL
P3 1003 NULL
P4 1004 1005
没有聚合就无法实现轴心 但以下是如何获取所需内容,输入所需的列数(条形码):
CREATE TABLE #table1(
ProductBarcode VARCHAR(10),
ProductID VARCHAR(10)
);
INSERT INTO #table1(ProductBarcode, ProductID)
VALUES
('1000' ,'P1'),
('1001' ,'P1'),
('1002' ,'P2'),
('1003' ,'P3'),
('1004' ,'P4'),
('1005' ,'P4');
WITH T AS(
SELECT 'Barcode' + RTRIM(LTRIM(STR( ROW_NUMBER() OVER(PARTITION BY ProductID ORDER BY ProductBarcode)))) AS BarcodeNum,
ProductBarcode,
ProductID
FROM #table1
)
SELECT * FROM T
PIVOT(MAX(ProductBarcode) FOR BarcodeNum IN([Barcode1], [Barcode2])) P
结果:
ProductID Barcode1 Barcode2
---------- ---------- ----------
P1 1000 1001
P2 1002 NULL
P3 1003 NULL
P4 1004 1005
谢谢你,库珀。我尝试了您编写的查询,我确实在Barcode1列下获得了条形码,但在Barcode2列下,它显示为空。@Misbah-我使用的是您的示例数据,对我来说效果很好。当使用pivot操作符查询除行之外的所有内容时,您是否得到了预期的结果?@Misbah Yanus-我发布了所有用于创建示例数据和查询的sql,这些数据和查询将产生预期的结果。我只是尝试从头开始创建并再次执行上述查询,结果成功。可能是我第一次运行它时的错误。谢谢!!为库珀干杯。我尝试了您编写的查询,我确实在Barcode1列下获得了条形码,但在Barcode2列下,它显示为空。@Misbah-我使用的是您的示例数据,对我来说效果很好。当使用pivot操作符查询除行之外的所有内容时,您是否得到了预期的结果?@Misbah Yanus-我发布了所有用于创建示例数据和查询的sql,这些数据和查询将产生预期的结果。我只是尝试从头开始创建并再次执行上述查询,结果成功。可能是我第一次运行它时的错误。谢谢!!干杯