悲しいことに、人気のある「Greatest-N-Per-Group」クエリの別のバリエーションですが、それは私のお尻を蹴っていて、 )可能な限り:ジョイントを持つグループごとの最大N:間違った最大値/最小値
Items
-----
ItemID
ProductName
Inventory
---------
InventoryID
ItemID
Condition
Price
そして、私は、各項目についてInventoryID、アイテムID、ItemNameの、条件、および最大の価格を表示するクエリを策定しようとしている:私は2つのテーブルを持っている
与えられた条件で
Inventory
---------
InventoryID ItemID Condition Price
INV123 ITEM001 NEW $3.99
INV001 ITEM001 NEW $3.79
INV031 ITEM001 USED $1.23
INV234 ITEM001 USED $1.99
やアイテム与えすなわち:
ItemID ItemName
ITEM001 Lg Widget
ITEM002 Sm Widget
私は期待したい:
ItemID ItemName Condition MaxPrice MaxPriceInventoryID
ITEM001 Lg Widget NEW $3.99 INV123
ITEM001 Lg Widget USED $1.99 INV234
私はこれをしようとしている:
残念ながらSELECT
ItemID, ItemName, b.condition, b.maxprice,
InventoryID as MaxPriceInventoryID
FROM
Items I join inventory v On i.ItemID= v.ItemID
join (
select inventory.ItemID, max(Price) as MaxPrice, condition
from inventory join Items on inventory.ItemID = Items.ItemID
group by inventory.ItemID, condition) as b
on b.ItemID = v.ItemID and b.MaxPrice = v.Price
ORDER BY
ItemName, Condition
、これは」doesnの望ましい結果を出す:それは散発的に再現するようだ指定された条件のアイテムの最大価格ではなく、すべての条件にわたってアイテムの最大価格を設定します。
アイデア?