当连接到具有多行的另一个表时,需要将我的结果限制为一行

时间:2017-11-13 16:03:11

标签: sql

表1

SaleID  |  Name  
123     |  John Doe
456     |  Jane Doe

表2

SaleID  |  ProductID    |  ProductCost  |  ProductSize
123     |  1            |  $200         |  Medium
123     |  2            |  $250         |  Large
123     |  3            |  $100         |  Small

结果:

SaleID     |  Name         | Product1Cost | Product1Size  | Product2Cost | Product2Size   | Product3Cost  | Product3Size
123        |  John Doe     | $200         | Medium
123        |  John Doe     |              |               | $250         | Large            
123        |  John Doe     |              |               |                               | $100          | Small

预期结果:

SaleID    |  Name        | Product1Cost  | Product1Size | Product2Cost  | Product2Size | Product3Cost  | Product3Size
123       |  John Doe    | $200          | Medium       | $250          | Large        | $100          | Small

这是我的问题:

Select    
    SaleID    = a.SaleID,
    Name = a.Name,
    Product1Cost = case when b.ProductID = '1'then b.Product1Cost end,
    Product1Size = case when b.ProductID = '1'then b.Product1Size end,
    Product2Cost = case when b.ProductID = '2'then b.Product2Cost end,
    Product2Size = case when b.ProductID = '2'then b.Product2Size end,
    Product3Cost = case when b.ProductID = '3'then b.Product3Cost end,
    Product3Size = case when b.ProductID = '3'then b.Product3Size end



from Table1 a

    OUTER APPLY
    (
        SELECT  *
        FROM Table2 b
        where a.SaleID = b.SaleID        
    ) b

1 个答案:

答案 0 :(得分:0)

您不需要applyjoingroup by应该有效:

Select a.SaleID, a.Name,
       Product1Cost = max(case when b.ProductID = '1' then b.Product1Cost end),
       Product1Size = max(case when b.ProductID = '1' then b.Product1Size end),
       Product2Cost = max(case when b.ProductID = '2' then b.Product2Cost end),
       Product2Size = max(case when b.ProductID = '2' then b.Product2Size end),
       Product3Cost = max(case when b.ProductID = '3' then b.Product3Cost end),
       Product3Size = max(case when b.ProductID = '3' then b.Product3Size end)
from Table1 a join
     Table2 b
     on a.SaleID = b.SaleID        
group by a.SaleID, a.Name;

您无需执行name = a.name。默认别名列名。

另外,如果ProductId是一个数字,那么不要在比较周围加上单引号。而不是= '1',请使用= 1