sql复杂计算

vfwfrxfs  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(341)

在sql中计算每个证券的损益

security side   quantity price
AAPL     BUY   2000     110.00
MSFT    BUY   1000      40.00
MSFT    SELL   500      38.00

结果应如下所示:

security realized_p&l
MSFT      -1000.00
AAPL
vd2z7a6w

vd2z7a6w1#

实际价格是卖出价减去买入价乘以卖出数量。

select a.`security`,
case when b.side is not null
then (b.price-a.price) * b.quantity
else '' end "realized_p&l"
from tbl a
left join tbl b
on a.`security`=b.`security` and b.side='SELL'
where a.side='BUY' 

result: 
security    realized_p&l
MSFT    -1000
AAPL

相关问题