3

この形式で 2 つのテーブルがあります。

在庫:

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

しかし、2番目の 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

Try this.

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テーブルに異なるエイリアスを配置した場合、それはうまくいきました。同じテーブルにprices2 回参加しているため、それらを区別するために別のエイリアスを使用する必要があります。

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 に答える