【问题标题】:SQL Server 2008 Pivot without Aggregation没有聚合的 SQL Server 2008 Pivot
【发布时间】:2012-02-20 03:50:45
【问题描述】:

我在尝试在桌子上执行枢轴时遇到问题。我想要的示例如下所示。

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;

任何帮助将不胜感激。

【问题讨论】:

    标签: sql sql-server sql-server-2008 pivot aggregation


    【解决方案1】:

    没有聚合就无法 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。
    • @Misbah - 我正在使用您的示例数据,对我来说很好。查询除带有枢轴运算符的行之外的所有内容时,您是否得到了预期的结果?
    • @Misbah Yanus - 我发布了所有用于创建您的示例数据和查询的 sql,它们将产生预期的结果
    • 我只是尝试从头开始创建并再次执行上述查询并且它有效。第一次运行它时可能是我的错。非常感谢!!干杯
    猜你喜欢
    • 2013-03-24
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 2014-12-30
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    相关资源
    最近更新 更多