SQL Severer - Pivot查询 - 将行转换为列

时间:2016-04-07 15:48:49

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

需要透视查询才能将列(Loc)转换为按(Item_No)

分组的行

现有表格:`

 ITEM_NO,   LOC,    Quantity,   Price,  WholSalePrice,  Category 
A18000, Loc1,   11, 100,    80, 1

A18001, LOC2,   22, 101,    81, 1

A18002, LOC3,   33, 102,    79, 1

A18003  ,LOC4,  44, 99, 78, 1

A18004, LOC5,   55, 98, 77, 1

B18000, Loc1,   888 ,10,    8,  2

B18001, LOC2,   999,    11, 7,  2

B18002, LOC3,   887,    12, 9,  2

B18003, LOC4,   885,    13, 6,  2

B18004, LOC5,   887,    14, 5,  2

将地点转移到行并获取相应的数量,价格,批发价格和类别

ITEM_NO,    Loc1-Quantity,  Loc1-Price, Loc1-WholSalePrice, Loc1-Category,  Loc2-Quantity,  Loc2-Price, Loc2-WholSalePrice, Loc2-Category,  Loc3-Quantity,  Loc3-Price, Loc3-WholSale Price,

    A18000, 11, 100,    80, 1,  22, 101,    81, 1,  33, 102,    79

    B18000, 888,    10, 8,  2,  999 ,11 ,7, 2,  887,    12  ,9

我正在尝试在上面的场景中应用以下查询,但不能正常工作..

USE AdventureWorks;
GO
SELECT VendorID, [250] AS Emp1, [251] AS Emp2, [256] AS Emp3, [257] AS Emp4, [260] AS Emp5
FROM 
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( [250], [251], [256], [257], [260] )
) AS pvt
ORDER BY pvt.VendorID;

感谢您的帮助!!

1 个答案:

答案 0 :(得分:0)

您可能最好只使用MAX(CASE WHEN)聚合来构建结果,而不是做多个支点。可以使用MINSUM代替MAX。这也可以像PIVOT一样动态完成。

SELECT  [ITEM_NO]               = LEFT(ITEM_NO, 5) + '0',
        [Loc1-Quantity]         = MAX(CASE WHEN [LOC] = 'Loc1' THEN [Quantity] END),
        [Loc1-Price]            = MAX(CASE WHEN [LOC] = 'Loc1' THEN [Price] END),
        [Loc1-WholSalePrice]    = MAX(CASE WHEN [LOC] = 'Loc1' THEN [WholSalePrice] END),   
        [Loc1-Category]         = MAX(CASE WHEN [LOC] = 'Loc1' THEN [Category] END),
        [Loc2-Quantity]         = MAX(CASE WHEN [LOC] = 'Loc2' THEN [Quantity] END),
        [Loc2-Price]            = MAX(CASE WHEN [LOC] = 'Loc2' THEN [Price] END),
        [Loc2-WholSalePrice]    = MAX(CASE WHEN [LOC] = 'Loc2' THEN [WholSalePrice] END),   
        [Loc2-Category]         = MAX(CASE WHEN [LOC] = 'Loc2' THEN [Category] END)     
        -- etc... 
FROM    myTable
GROUP BY LEFT(ITEM_NO, 5)