sql select 旋转多个表

sql select pivot multiple tables

我看到过类似的问题,但是 none 完全符合我正在尝试做的事情。

3 tables: 产品、计划、绩效。

性能 table 除了服务于一个目的之外,还代表了另外两个 table 之间的多对多关系。

让我们调用链接字段:

performance.PlanID = plan.PlanID
performance.ProductID = product.ProductID

对此有 3 个感兴趣的领域:

product.ProductName
plan.Status (Live or Pending)
performance.Capacity

我想编写一个 select 查询,结果如下:

ProductName
LiveCapacity
PendingCapacity

我在查询的 FROM (SELECT...) 部分尝试了一个具有所需内部联接的数据透视表,但我似乎无法正确处理。

这样的查询会产生什么结果?

SELECT product.ProductName as Name, plan.Status as Status, 
    performance.Capacity as Capacity
FROM product, plan, performance
WHERE performance.PlanID <> plan.PlanID 
    AND performance.ProductID <> product.ProductID
;

我建议您始终使用显式联接。

根据您的评论更新:

SELECT product.ProductName as Name
     , plan.Status as Status
     , SUM(performance.Capacity) as Capacity
FROM product
INNER JOIN plan
   ON performance.PlanID = plan.PlanID
INNER JOIN performance
   ON performance.ProductID = product.ProductID
GROUP BY product.ProductName
       , plan.Status as Status 

枢轴示例。

SELECT 
    t.ProductName,
    [Live] AS LiveCapacity,
    [Pending] AS PendingCapacity
FROM 
(
    SELECT  product.ProductName,
          performance.Capacity,
          plan.Status 
    FROM    product 
          JOIN performance ON performance.ProductID = product.ProductID
          JOIN plan ON performance.PlanID = plan.PlanID
) t
PIVOT (
    SUM(Capacity)
    FOR Status IN ([Live],[Pending])
) p

非枢轴示例

SELECT  product.ProductName,
        SUM(CASE WHEN plan.Status = 'Live' THEN performance.Capacity END) as LiveCapacity,
        SUM(CASE WHEN plan.Status = 'Pending' THEN performance.Capacity END) as PendingCapacity
FROM    product 
        JOIN performance ON performance.ProductID = product.ProductID
        JOIN plan ON performance.PlanID = plan.PlanID
GROUP BY product.ProductName