首次发布;在这里找不到解决我的问题的任何东西。计算SQL中的净贸易头寸
我有大约63万项,这里样品输入一个交易表:
dealid deal_counterparty_id deal_instrument_id deal_type deal_amount
20001 703 1010 B 3588.81
20002 701 1001 S 3412.81
20003 701 1004 B 8527.11
20004 701 1011 S 2441.77
20005 703 1010 B 3633.33
20006 702 1011 S 2415.16
20007 704 1003 S 1426.14
20008 701 1012 B 1858.82
20009 703 1009 B 3571.77
我想找到的每个位置每个经销商实现的位置。即交易商对于1个交易对手有1笔交易有成千上万的交易,那么该交易对手的净头寸是多少?
我想要3列:deal_counterparty_id,deal_instrument.id,净位置。因为我有20台仪器(1001至20年)只有4对手(701,702,703,704),所述采样输出是这样的:
deal_counterparty_id deal_instrument_id net_position
701 1001 5833.34
701 1002 -3994.21
701 1003 30300.00
...
702 1001
我的代码(0得到的结果):
select buy.deal_counterparty_id, buy.deal_instrument_id, sum(buy.deal_amount) - sum(sell.deal_amount) as net_position
from (select deal_id, deal_counterparty_id, deal_instrument_id, deal_type, deal_amount
from deal where deal_type = 'B') as buy
join (select deal_id, deal_counterparty_id, deal_instrument_id, deal_type, deal_amount
from deal where deal_type = 'S') as sell
on buy.deal_instrument_id = sell.deal_instrument_id
group by buy.deal_counterparty_id, buy.deal_instrument_id;
谢谢!
样本输入输出+?不像每个开发者都是财务人 – Steve
样本输入是上面的表格图像,样本输出将是: deal_counterparty_id || deal_instrument_id ||净头寸 701 || 1001 || -3495.40 701 || 1002 || 7825.01 ... 701 || 1020 || 1938.23 702 || 1001 || 4726.44 –
而不是'JOIN's,我会从'IF(deal_type ='B',deal_amount, - deal_amount)net_amount'开始。 –