复杂匹配并加入PostgreSQL

问题描述 投票:1回答:1

我有以下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) ;

我正在寻找以下结果:

  • txn_id
  • 金额

  • sell_price(查找打开或关闭的txns中的哪一个是卖出cust_txn。将该交易的货币,时间戳和exch_txn_type与bc_quotes表中的货币,时间戳和quote_type相匹配,然后选择报价)

  • 买入价格(查找开盘价或收盘价中的哪一个是买入csut_txn。将bc_quotes表中的货币,时间戳记和exch_txn_type与货币,时间戳记和quote_type匹配,然后选择报价)

postgresql
1个回答
0
投票

我的回答是假设opening_txnsclosing_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_txnsclosing_txns共享相同的列,您可以使用UNION有效地将两个结果集合并为一个txns结果集。
  • 然后您可以使用LEFT JOIN来匹配txns使用它们提供的条件ON子句。
  • 最后,您可以使用条件CASE语句在SELECT中进行区分以区分'SELL''BUY交易;如果交易为'BUY'(分别为'SELL'),则buy_price列将为quotesell_price将为NULL

最终结果集包含以下列:txn_idamountsell_pricebuy_price

我希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.