使用PIVOT 和 UNPIVOT

 

使用PIVOT 和 UNPIVOT

使用PIVOT 和 UNPIVOT

答案:

 

SELECT  SalesPersonID,  [ 1 ]   AS  JAN, [ 2 ]   AS  FEB,  [ 3 ]   AS  MAR,  [ 4 ]   AS  APR
FROM  
(
    
SELECT  SalesPersonID,  DATEPART (MM,OrderDate)  AS  MON
    
FROM  Sales.SalesOrderHeader
    
WHERE   DATEPART (yyyy,OrderDate)  =   2002
) S

PIVOT 
(
    
COUNT (MON)  FOR  MON  IN  ( [ 1 ] , [ 2 ] , [ 3 ] , [ 4 ] )
)
AS  P

 

SELECT VendorID, [164] AS Emp1, [198] AS Emp2, [223] AS Emp3, [231] AS Emp4, [233] AS Emp5

FROM 

(SELECT PurchaseOrderID, EmployeeID, VendorID

FROM Purchasing.PurchaseOrderHeader) p

PIVOT

(

COUNT (PurchaseOrderID)

FOR EmployeeID IN

( [164], [198], [223], [231], [233] )

) AS pvt

ORDER BY pvt.VendorID;
VendorID    Emp1        Emp2        Emp3        Emp4        Emp5

1           4           3           5           4           4

2           4           1           5           5           5

3           4           3           5           4           4

4           4           2           5           5           4

5           5           1           5           5           5
CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,

    Emp3 int, Emp4 int, Emp5 int);

GO

INSERT INTO pvt VALUES (1,4,3,5,4,4);

INSERT INTO pvt VALUES (2,4,1,5,5,5);

INSERT INTO pvt VALUES (3,4,3,5,4,4);

INSERT INTO pvt VALUES (4,4,2,5,5,4);

INSERT INTO pvt VALUES (5,5,1,5,5,5);

GO

--Unpivot the table.

SELECT VendorID, Employee, Orders

FROM 

   (SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5

   FROM pvt) p

UNPIVOT

   (Orders FOR Employee IN 

      (Emp1, Emp2, Emp3, Emp4, Emp5)

)AS unpvt;

GO
VendorID   Employee   Orders

1      Emp1         4

1      Emp2         3

1      Emp3         5

1      Emp4         4

1      Emp5         4

2      Emp1         4

2      Emp2         1

2      Emp3         5

2      Emp4         5

2      Emp5         5

...

你可能感兴趣的:(使用)