Below table shows the user_portfolio
and STOCK_DATA_TRANSPOSED
.
In the first table, User 1 has a portfolio of 4 stocks added on the date 2019-12-30.
In the second table, we have the data for each stock the next 5 days.
I would like to get the difference for each stock for each day, to be able to sum it and create a graph that shows the change in profit for the users portfolio across all Names.
How can I do this the smartest way?
select * from user_portfolio where User_ID = 1
ID Name Date Price User_ID
4 SO 2019-12-30 64.44 1
5 RWE.DE 2019-12-30 32.11 1
6 OPTT 2019-12-30 2.14 1
7 MMM 2019-12-30 205.11 1
Select Date, Name, Price from STOCK_DATA_TRANSPOSED
Date Name Price
2019-12-31 MMM 176.42
2020-01-02 MMM 180.00
2020-01-03 MMM 178.45
2020-01-06 MMM 178.62
2020-01-07 MMM 177.90
2019-12-31 SO 63.70
2020-01-02 SO 62.62
2020-01-03 SO 62.56
2020-01-06 SO 62.81
2020-01-07 SO 62.62
2020-01-02 RWE.DE 26.96
2020-01-03 RWE.DE 26.84
2020-01-06 RWE.DE 26.45
2020-01-07 RWE.DE 27.05
2020-01-08 RWE.DE 27.17
2019-12-31 OPTT 0.87
2020-01-02 OPTT 0.88
2020-01-03 OPTT 0.84
2020-01-06 OPTT 0.86
2020-01-07 OPTT 0.85
Please see this SQLFIDDLE for test data: http://sqlfiddle.com/#!9/b81035 You can ignore the timestamp and id column in STOCK_DATA_TRANSPOSED.
Desired output could look something like this ( I am aware prices from above table do no match with Date_Price):
Name Date Price User_ID Date_Diff Date_Price % Diff
SO 2019-12-30 64.44 1 2019-12-31 176.4199982 173.77%
RWE.DE 2019-12-30 32.11 1 2019-12-31 180 460.57%
OPTT 2019-12-30 2.14 1 2019-12-31 178.4499969 8238.78%
MMM 2019-12-30 205.11 1 2019-12-31 178.6199951 -12.92%
SO 2019-12-30 64.44 1 2020-01-02 177.8999939 176.07%
RWE.DE 2019-12-30 32.11 1 2020-01-02 62.61999893 95.02%
OPTT 2019-12-30 2.14 1 2020-01-02 62.56000137 2823.36%
MMM 2019-12-30 205.11 1 2020-01-02 62.81000137 -69.38%
SO 2019-12-30 64.44 1 2020-01-03 62.61999893 -2.82%
RWE.DE 2019-12-30 32.11 1 2020-01-03 33.11 3.11%
OPTT 2019-12-30 2.14 1 2020-01-03 0.8799999952 -58.88%
MMM 2019-12-30 205.11 1 2020-01-03 0.8399999738 -99.59%
Meaning each entry in portfolio, will be compared to each Date_Diff after Date.
% Diff is calculated by: (Date_Price - Price)/Price