I am developing a Stocks management application, the Portfolio register table has 4 columns, other than date and registry_key, and it looks like this:
----------------------------------------
| stock_key | user_key | units | price |
----------------------------------------
| fund_a | user_1 | 1000 | 100.35|
| fund_c | user_2 | 4000 | 101.55|
| fund_d | user_3 | 2000 | 105.65|
| fund_a | user_1 | 1500 | 101.45|
| fund_b | user_1 | 500 | 103.35|
----------------------------------------
I wish to select the portfolio of user_1 with distinct stock_key. Plus I need the price as the aggregate total paid over the number of units. For example:
For user_1 the result should be:
[
{fund_key: "fund_a", units: sum(1000,1500), price: sum(1000*100.35,1500*101.45)/sum(1000,1500)},
{fund_key: "fund_b", units: 500, price: 103.35}
]
This is important because once the user has brought more units of the same stock at a lower/higher price than before, the accumulated stocks price is averaged out.