SQL Server 2008不支持汇总
问题描述:
我正面临着一个问题,试图在表上执行一个数据透视表。我想要的样本如下所示。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;
任何帮助将不胜感激。
答
没有办法让PIVOT没有汇总。
但在这里是如何得到你想要的东西,但是输入的列(条码)你想:
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列下,它显示了所有NULL。 – 2012-01-27 03:35:10
@Misbah - 我使用您的示例数据,为我工作得很好。查询除了数据透视操作符以外的所有内容时是否会得到预期的结果? – 2012-01-27 03:42:27
@Misbah Yanus - 我发布了所有用于创建示例数据和查询的SQL,用于创建预期结果 – 2012-01-27 03:46:42