I have a MySql table consisting of daily stock quotes (open, high, low, close and volume) which I\'m trying to convert into weekly data on the fly. So far, I have the follow
You will likely need to COALESCE
function to get the first value. However, you need to make sure that days without data (weekends and holidays) have a null value for _open
on those days without data.
Usage would be:
SELECT MIN(_low), MAX(_high), AVG(_volume), COALESCE(_open)
CONCAT(YEAR(_date), "-", WEEK(_date)) AS myweek
FROM mystockdata
GROUP BY myweek
ORDER BY _date;
For the last() value, I can only think of a pretty hacky solution, which would be to use GROUP_CONCAT
and then string manipulation to get the last value from the list. So perhaps something like this:
SELECT MIN(_low), MAX(_high), AVG(_volume), COALESCE(_open), SUBSTRING_INDEX(GROUP_CONCAT(_close), ',', -1)
CONCAT(YEAR(_date), "-", WEEK(_date)) AS myweek
FROM mystockdata
GROUP BY myweek
ORDER BY _date;
Note you could also use the GROUP_CONCAT
approach for the first item instead of coalesce if you wanted consistent looking query
SELECT MIN(_low), MAX(_high), AVG(_volume), SUBSTRING_INDEX(GROUP_CONCAT(_open), ',', 1), SUBSTRING_INDEX(GROUP_CONCAT(_close), ',', -1)
CONCAT(YEAR(_date), "-", WEEK(_date)) AS myweek
FROM mystockdata
GROUP BY myweek
ORDER BY _date;
For GROUP_CONCAT
to work properly you also need to make sure the dates without values have null in _open
and _close
fields.