3

我有两个这种形式的表:

存货:

Units   InDate OutDate

1000     11/4   12/4

2000     13/4   14/4

价格:

Date Price
11/4    5
12/4    4
13/4    6
14/4    7

我想建立下表:

Units   InDate OutDate InPrice   OutPrice

1000     11/4    12/4     5       4

2000     13/4    14/4     6       7

我想我应该使用类似的东西:

Select *
FROM Inventory
LEFT OUTER JOIN Prices ON Inventory.InDate = Prices.Date
LEFT OUTER JOIN Prices ON Inventory.OutDate = Prices.Date

但是第二个 OUTER JOIN 似乎把事情搞砸了。

我怎样才能达到这个结果?

4

3 回答 3

4
Select
  Units,   
  InDate,
  OutDate,
  P1.Price as InPrice,
  P2.Price as OutPrice
FROM Inventory
LEFT OUTER JOIN Prices as P1 ON Inventory.InDate = P1.Date
LEFT OUTER JOIN Prices as P2 ON Inventory.OutDate = P2.Date
于 2012-11-20T10:58:36.410 回答
3

尝试这个。

SELECT Inventory.Units, Inventory.InDate, Inventory.OutDate, InPrices.Price AS InPrice, OutPrices.Price AS OutPrice
FROM Inventory
LEFT OUTER JOIN Prices AS InPrices ON Inventory.InDate = InPrices.Date
LEFT OUTER JOIN Prices AS OutPrices ON Inventory.OutDate = OutPrices.Date
于 2012-11-20T10:59:48.270 回答
2

您当前的查询非常接近正确。如果您在桌子上放置不同的别名,prices那么它会起作用。由于您在同一张表上加入prices两次,因此您需要使用不同的别名来区分它们:

select i.units,
  i.indate,
  i.outdate,
  inPrice.price,  
  outPrice.price
from inventory i
left join prices inPrice  -- first join with alias
  on i.indate = inPrice.date
left join prices outPrice  -- second join with alias
  on i.outdate = outPrice.date

请参阅带有演示的 SQL Fiddle

于 2012-11-20T11:02:21.070 回答