我有一个与它有M-M关系的货币(Rec_ID,货币)表,它会产生CurrencyExchangeRate表(Rec_ID,Currency_FK1 AS'FROM',Currency_FK2 AS'TO,Exchange_Rate)
现在我需要一个查询来执行货币rec_id的所有组合(不允许重复), 以及汇率或无效。如果货币中有3条记录,那么查询应返回6行。
由于
答案 0 :(得分:1)
如果您想要所有组合(甚至那些没有定义费率的组合),请先将其与自身连接,然后再加上费率
SELECT
c1.currency AS [From], c2.currency AS [To] , cer.Exchange_Rate
FROM
currency c1 JOIN currency c2 ON c1.rec_id <> c2.rec_id
LEFT OUTER JOIN CurrencyExchangeRate cer ON c1.rec_id = cer.[from]
AND c2.rec_id = cer.[to]
答案 1 :(得分:0)
SELECT
CCY1, CCY2, CER.Exchange_Rate
FROM
(
SELECT
c1.rec_id AS rec_id1, c1.currency AS CCY1,
c2.rec_id AS rec_id2, c2.currency AS CCY2
FROM
currency c1
CROSS JOIN --all combinations...
currency c2
WHERE
c1.rec_id <> c2rec_id -- ...removes same pairs
) foo
LEFT JOIN -- ...get matching FX pairs
CurrencyExchangeRate CER ON foo.rec_id1 = cer.[from] AND foo.rec_id2 = cer.[to]