I’m trying to update a table containing stock pricing information to include the returns of those stocks if held for different time periods. The return is inserted at the start of the time period.
The following SELECT statement calculates the values I’m looking for, for 3 and 6 month hold periods. The table is price_returns
SELECT
curr.date, curr.company, curr.price,
(mo3.price - curr.price)/curr.price AS 3MONTH_RETURN,
(mo6.price - curr.price)/curr.price AS 6MONTH_RETURN
FROM
price_returns AS curr
LEFT OUTER JOIN
price_returns AS mo3
ON
((curr.date = LAST_DAY(mo3.date - INTERVAL 3 MONTH)) AND (curr.company = mo3.company))
LEFT OUTER JOIN
price_returns AS mo6
ON
((curr.date = LAST_DAY(mo6.date - INTERVAL 6 MONTH)) AND (curr.company = mo6.company))
Order by
curr.company, curr.date;
I would like convert this SELECT to an UPDATE into the table price_returns and insert 3MONTH_RETURN and 6MONTH_RETURN into columns ret_3mth and ret_6mth.
This is what I have, but it’s not executing the update correctly. The join appears to be working as it’s matched the correct number of rows, but it doesn’t change any rows.
* Update *
Not sure why, but this code below now appears to be working. Sorry for the confusion. I still haven’t worked out what happened and why it wasn’t but now is working. User error I’m sure.
* Update *
UPDATE
price_returns AS curr
LEFT OUTER JOIN
price_returns AS mo3
ON
((curr.date = LAST_DAY(mo3.date - INTERVAL 3 MONTH)) AND (curr.company = mo3.company))
LEFT OUTER JOIN
price_returns AS mo6
ON
((curr.date = LAST_DAY(mo6.date - INTERVAL 6 MONTH)) AND (curr.company = mo6.company))
SET
curr.ret_3mth = (mo3.price - curr.price)/curr.price,
curr.ret_6mth = (mo6.price - curr.price)/curr.price;
Thanks for your help.
you can do this using a subquery (http://dev.mysql.com/doc/refman/5.0/en/subqueries.html)
So in the brackets there is the subquery, where you would past that entire select code you have above (the first mysql code that is)