如何使用自我联接的数据透视表

时间:2016-11-18 13:28:05

标签: sql sql-server for-loop join pivot

在这里的一些问题中,我得到了这段代码

SELECT s.CompanyName ,[250] AS ProductName, [251] AS ProductName, pc.CategoryID
FROM Suppliers s INNER JOIN (SELECT SupplierID, CategoryID
                         FROM Products
                         GROUP BY SupplierID,CategoryID
                         HAVING COUNT(1) = 2) pc ON (s.SupplierID = pc.SupplierID)
             INNER JOIN Products p ON(s.SupplierID = p.SupplierID AND pc.CategoryID = p.CategoryID)
PIVOT
(
  p.ProductName
  FOR SupplierID IN ([250], [251]) AS pvt
)
ORDER BY pvt.CompanyName

我尝试使用像[Micorsoft]那样的枢轴,但我在for循环附近遇到语法错误

没有Pivot的结果是DEMO

+------------------------------------+---------------------------------+----------------+
|                CompanyName         |              ProductName        |     CategoryID |   
+------------------------------------+---------------------------------+----------------+
| Exotic Liquids                     | Chai                            | Beverages      |
| Exotic Liquids                     | Chang                           | Beverages      |
| Aux joyeux ecclésiastiques         | Côte de Blaye                   | Beverages      |
| Aux joyeux ecclésiastiques         | Chartreuse verte                | Beverages      |
| Grandma Kelly's Homestead          | Grandma's Boysenberry Spread    | Condiments     |
| Grandma Kelly's Homestead          | Northwoods Cranberry Sauce      | Condiments     |
| Zaanse Snoepfabriek                | Zaanse koeken                   | Confections    |
| Zaanse Snoepfabriek                | Chocolade                       | Confections    |
| Karkki Oy                          | Maxilaku                        | Confections    |
| Karkki Oy                          | Valkoinen suklaa                | Confections    |
| Cooperativa de Quesos 'Las Cabras' | Queso Cabrales                  | Dairy Products |
| Cooperativa de Quesos 'Las Cabras' | Queso Manchego La Pastora       | Dairy Products |
| Gai pâturage                       | Raclette Courdavault            | Dairy Products |
| Gai pâturage                       | Camembert Pierrot               | Dairy Products |
| PB Knäckebröd AB                   | Gustaf's Knäckebröd             | Grains/Cereals |
| PB Knäckebröd AB                   | Tunnbröd                        | Grains/Cereals |
| Pasta Buttini s.r.l.               | Gnocchi di nonna Alice          | Grains/Cereals |
| Pasta Buttini s.r.l.               | Ravioli Angelo                  | Grains/Cereals |
| Ma Maison                          | Tourtière                       | Meat/Poultry   |
| Ma Maison                          | Pâté chinois                    | Meat/Poultry   |
| New England Seafood Cannery        | Boston Crab Meat                | Seafood        |
| New England Seafood Cannery        | Jack's New England Clam Chowder | Seafood        |
| Lyngbysild                         | Rogede sild                     | Seafood        |
| Lyngbysild                         | Spegesild                       | Seafood        |
+------------------------------------+---------------------------------+----------------+

并使用透视图,它应该DEMO

    CompanyName 
    ProductName
    ProductName2
    Category

1
    Exotic Liquids
    Chai
    Chang
    Beverages

2
    Aux joyeux ecclésiastiques
    Côte de Blaye
    Chartreuse verte
    Beverages

3
    Grandma Kelly's Homestead
    Grandma's Boysenberry Spread
    Northwoods Cranberry Sauce
    Condiments

4
    Zaanse Snoepfabriek
    Zaanse koeken
    Chocolade
    Confections

5
    Karkki Oy
    Maxilaku
    Valkoinen suklaa
    Confections

2 个答案:

答案 0 :(得分:1)

这并不需要透视,只需在每行中添加一行row_id,然后使用GROUP BY

进行排列

<强> SQL DEMO

WITH add_id as (
    SELECT *,
           row_number() over (partition by [CompanyName] ORDER BY [ProductName]) as rn
    FROM Table1        
)       
SELECT [CompanyName],
       MAX(CASE WHEN rn = 1 THEN [ProductName] END) as [ProductName1],
       MAX(CASE WHEN rn = 2 THEN [ProductName] END) as [ProductName2],
       MAX([Category]) as [Category]
FROM add_id
GROUP BY [CompanyName]

<强>输出

enter image description here

修改

如果只有两个产品且总是两个产品,则可以制作没有row_number的简单版本。如果只有一个Product,那么Product1Product2将是相同的

SELECT [CompanyName],
       MIN([ProductName]) as [ProductName1],
       MAX([ProductName]) as [ProductName2],
       MAX([Category]) as [Category]
FROM Table1
GROUP BY [CompanyName]

答案 1 :(得分:0)

首先,<aggregation function>缺失。并且您必须为数据透视而不是值列表。加Pvt别名没有CompanyName列 试试这个语法

SELECT s.CompanyName ,[250] AS ProductName1, [251] AS ProductName2, pc.CategoryID
FROM Suppliers s 
INNER JOIN (SELECT SupplierID, CategoryID
            FROM Products
            GROUP BY SupplierID,CategoryID
            HAVING COUNT(1) = 2) pc ON (s.SupplierID = pc.SupplierID)
INNER JOIN Products p ON(s.SupplierID = p.SupplierID AND pc.CategoryID = p.CategoryID)
PIVOT
(
  max(p.ProductName)
  FOR s.SupplierID IN ([250], [251]) 
) AS pvt
ORDER BY s.CompanyName