我有以下3个表:开仓交易,平仓交易和另一个带有价格(或报价)的交易。
打开和关闭是彼此的镜像。如果一个买入,另一个卖出。它们由相同的txn_id匹配。
INSERT INTO opening_txns (txn_id,txn_timestamp,cust_txn_type,exch_txn_type,currency,amount) VALUES
('0001','2019-01-16 09:00:00.000','SELL','BUY','Euro',1000)
,('0002','2019-01-25 09:00:00.000','BUY','SELL','Euro',1000)
,('0003','2019-01-30 09:00:00.000','BUY','SELL','Euro',1000)
,('0004','2019-02-06 09:00:00.000','SELL','BUY','Euro',1000)
,('0005','2019-02-12 09:00:00.000','SELL','BUY','Euro',1000)
,('0006','2019-02-25 09:00:00.000','BUY','SELL','Euro',1000)
,('0007','2019-03-21 09:00:00.000','BUY','SELL','Euro',1000)
;
INSERT INTO closing_txns (txn_id,txn_timestamp,cust_txn_type,exch_txn_type,currency,amount) VALUES
('0001','2019-03-29 12:00:00.000','BUY','SELL','Euro',1000)
,('0002','2019-03-29 12:00:00.000','SELL','BUY','Euro',1000)
,('0003','2019-03-29 12:00:00.000','SELL','BUY','Euro',1000)
,('0004','2019-03-29 12:00:00.000','BUY','SELL','Euro',1000)
,('0005','2019-03-29 12:00:00.000','BUY','SELL','Euro',1000)
,('0006','2019-03-29 12:00:00.000','SELL','BUY','Euro',1000)
,('0007','2019-03-29 12:00:00.000','SELL','BUY','Euro',1000)
;
INSERT INTO bc_quotes (quote_timestamp,currency,unit,quote_type,"quote") VALUES ('2019-02-25 09:00:00.000','Euro',1,'SELL',1.1375) ,('2019-02-25 09:00:00.000','Euro',1,'BUY',1.1355) ,('2019-03-21 09:00:00.000','Euro',1,'SELL',1.1416) ,('2019-03-21 09:00:00.000','Euro',1,'BUY',1.1392) ,('2019-03-29 12:00:00.000','Euro',1,'BUY',1.1225) ,('2019-03-29 12:00:00.000','Euro',1,'SELL',1.1246) ;
我正在寻找以下结果:
金额
sell_price(查找打开或关闭的txns中的哪一个是卖出cust_txn。将该交易的货币,时间戳和exch_txn_type与bc_quotes表中的货币,时间戳和quote_type相匹配,然后选择报价)
买入价格(查找开盘价或收盘价中的哪一个是买入csut_txn。将bc_quotes表中的货币,时间戳记和exch_txn_type与货币,时间戳记和quote_type匹配,然后选择报价)
我的回答是假设opening_txns
和closing_txns
的列属于同一类型。
请尝试以下操作,并告诉我它是否适合您:
WITH txns AS (
SELECT
txn_id,
amount,
currency,
timestamp,
exch_txn_type
FROM opening_txns
UNION
SELECT
txn_id,
amount,
currency,
timestamp,
exch_txn_type
FROM closing_txns
)
SELECT
txn_id,
amount,
CASE WHEN cust_txn_type = 'SELL' THEN quote ELSE NULL END AS sell_price,
CASE WHEN cust_txn_type = 'BUY' THEN quote ELSE NULL END AS buy_price
FROM txns T
LEFT JOIN bc_quotes Q
ON (T.currency = Q.currency AND T.timestamp = Q.timestamp AND T.exch_txn_type = Q.quote_type);
说明:
txns
是用于帮助澄清查询的common table expression。opening_txns
和closing_txns
共享相同的列,您可以使用UNION
有效地将两个结果集合并为一个txns
结果集。LEFT JOIN
来匹配txns
使用它们提供的条件ON
子句。CASE
语句在SELECT
中进行区分以区分'SELL'
和'BUY
交易;如果交易为'BUY'
(分别为'SELL'
),则buy_price
列将为quote
,sell_price
将为NULL
。最终结果集包含以下列:txn_id
,amount
和sell_price
,buy_price
。
我希望这会有所帮助。