一起使用PIVOT和JOIN

时间:2011-09-11 20:06:00

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

考虑此查询:

SELECT [Order Details].OrderID,
   c.CategoryName,
   COUNT(c.CategoryID)
FROM   [Order Details]
   INNER JOIN Products p
        ON  p.ProductID = [Order Details].ProductID
   INNER JOIN Categories c
        ON  c.CategoryID = p.CategoryID
GROUP BY
   [Order Details].OrderID,
   c.CategoryName
ORDER BY
   [Order Details].OrderID

此查询返回此结果(Usnig Northwind数据库):

enter image description here

我想使用Pivot with Join来获得这样的结果:

OrderID    Condiments    Produce    Seafood    Condiments    Grains/Cereals    ...
--------------------------------------------------------------------------------------
10250           1            1           1          0              0             ...
10251           1            0           0          0              2             ...
...

我怎么能这样做?

由于

1 个答案:

答案 0 :(得分:5)

WITH T
     AS (SELECT [Order Details].OrderID,
                c.CategoryName,
                c.CategoryID
         FROM   [Order Details]
                INNER JOIN Products p
                  ON p.ProductID = [Order Details].ProductID
                INNER JOIN Categories c
                  ON c.CategoryID = p.CategoryID)
SELECT *
FROM   T PIVOT ( COUNT (CategoryID) FOR CategoryName IN ( 
       [Beverages],
       [Condiments],
       [Confections], 
       [Dairy Products], 
       [Grains/Cereals],
       [Meat/Poultry],
       [Produce],
       [Seafood]) ) AS pvt
ORDER  BY OrderID