SQL复杂计算

时间:2018-05-01 22:59:04

标签: mysql sql conditional aggregation

计算SQL中每个安全性的P& L

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

1 个答案:

答案 0 :(得分:0)

P& LRealized是卖出价格减去买入价格乘以卖出数量。

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