2016-10-24 5 views
2

私はかなり新しいSQLです。私は、顧客から要求された製品オプションのペアを格納するテーブルを持っています。このテーブルには、次のようになります。SQL Server - 利用可能なストックオプションのペアを選択

**OptionID, CustomerID, ProductID** 
1,   15,   338 
2 ,   15,   161 
3,   15,   777   
4,   22,   999 
5,   22,   614 
6,   22,   7411 
7,   22,   2301 
8,   22,   2254 

私が利用可能な製品のペアのリストで終わるしたい、など、在庫データを確認するとき:

**CustomerID, Product 1, Product2** 
    15  , 338  , 298 
    15  , 161  , 241 

は、在庫データは次のようになります。

**StockData** 
298 
338 
161 
91 
241 
96 
99 
102 
104 
+3

製品をペアリングするための基準は何ですか? 338と298は一致し、161と241は一致する。彼らは両方とも15のCustomerIDを使用しますが、特にそれらのペアは互いにペアになっていますか? – kingdamian42

+0

返事をありがとう、私はちょうど出力の例としてそれを使用しました。基準は、顧客ID 15の場合、すべてが在庫であれば、要求されたすべてのオプションをチェックし、すべての商品が返品されていない場合は在庫がある商品のペアを返却する必要があります –

答えて

1

あなたが望むすべては、顧客ごとの在庫の2つの製品オプションのすべての組み合わせであれば、このようなselfjoinが動作するはずです:

select p1.customerID, p1.productID product1, product2.productID product2 
from options p1 
join options p2 on p2.customerID=p1.customerID 
and p1.productID<p2.productID 
where p1.productID in (select productID from stock) 
and p2.productID in (select productID from stock) 

あなたはオプション番号を優先し、製品の使用可能な最初のペアを望んでいただろうならば、あなたはこれを行うことができますが:

;with productpairs as 
(
    select p1.customerID, p1.productID product1, product2.productID product2, 
    p1.optionID+p2.optionID priority 
    from options p1 
    join options p2 on p2.customerID=p1.customerID 
    and p1.productID<p2.productID 
), 
orderedpairs as 
(
    select *, ROW_NUMBER() OVER (PARTITION BY customerID ORDER BY priority) AS rn 
    from productpairs 
) 
select customerID, product1, product2 
from oderedpairs 
where rn=1 
+0

ありがとう、私はこのメソッドを試してみます –

関連する問題