Wednesday, December 16, 2015

Hw To Match Stock Holdings with any Stock Model Using SQL Full Outer Join

Problem
Here's a nice SQL challenge that I have done recently.
There are 2 friends Jack and Julie.
Jack has a list of holdings that represents stock name and amount he owns.
Julie has a Model that represents stock name and percentage she owns of the stock.
for the holding table, the Total amount is $1000.
For the Model table, the Total percentage is 100%


We would like to map Jack's holdings to Julie's Model.
We have a table of orders represented by stock name, amount, and operation type.
We are looking for a list of stocks that we need to buy or sell in order to match holdings with any given model.
Here's an example.

Solution
Using full outer Join we can provide a simple, and easy to understand solution.  We use left or right outer join most of the time, and It's very rare to use Full outer join. 
Full outer join provides you with all records from both tables a long with the matching records of each other. It's like a union of Left join and right join.


Simply Left join and Union concepts are all what we need to resolve this problem in a single SQL query.



No comments:

Post a Comment