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.



Friday, March 27, 2015

Filter dates in a date range

Problem
We need to come with a list of dates where our service is online. Considering another list of date range(From through dates) where our service is down for maintenance.
We are looking for a date range of days, months, and may be years. So we might get a huge list of dates.
The 3 blocks on the image below represents down time of a service.
Solution
There are multiple ways to approach this problem but I need a smart way to implement it in O(1) or O(n) in the worst case.
Since I'm using C#. I can use a dictionary of datetime as a key and bool as It's value.
The dictionary keys will be all available dates with default value of true(service is available).
Since It's a dictionary, the insert operation is O(1).
Then we will go through each down time period and update the value of the Date key to true if the date is a key in our dictionary. 
Then we will return a list of Keys where the value is false.

Results
List of dates where our service is online and functioning.