Is there a way to convert the following into a query without subqueries (or with a lesser number of subqueries) in order to make it faster.
select ( +(select sum(coalesce(quantity,0)) from transaction where
buyer_number = 101 and stock_id = 22 and status = \'bought\')
-(select sum(coalesce(quantity,0)) from transaction where
seller_number = 101 and stock_id = 22 and status = \'sold\')
) as balance_primary,
( +(select sum(coalesce(quantity,0)) from transaction where
buyer_number = 101 and stock_id = 22 and status = \'received\')
-(select sum(coalesce(quantity,0)) from transaction where
seller_number = 101 and stock_id = 22 and status = \'gifted\')
) as balance_secondary
All the
WHEREclauses in the subqueries use the conditionstock_id = 22, so it can be moved in theWHEREclause of the final query.You can get the sums with conditional aggregation:
You could also write the
WHEREclause as: