Just like MIN()
and AVG()
i sometimes need the most common occuring value (AKA the mode) of an integer value. This can be obtained as such:
SELECT column, COUNT(*) AS x
FROM table
GROUP BY column
ORDER BY x DESC
LIMIT 1
And thats quite a mouthful. I'd really like to use it like: MODE()
SELECT AVG(`sTemperature`), MODE(`sSwitch`), MODE(`sDoor`)
FROM `stats`;
Is there a way to make the above query work for Integers?
For Booleans, i figure ROUND(AVG())
is fine.
Its possible to define functions in a MySQL DB, but can they work on datasets as MIN() or AVG() does?
Because i use it a lot inside things like:
INSERT INTO `statsaggregates` (
`saMeasurements`, `saTemperature`, `saSwitch`, `saDoor`
) SELECT
COUNT(*) as 'saMeasurements',
AVG(`sTemperature`) as 'saTemperatureAvg',
MIN(`sTemperature`) as 'saTemperatureMin',
MAX(`sTemperature`) as 'saTemperatureMax',
MODE(`sSwitch`) as 'saSwitch',
MODE(`sDoor`) as 'saDoor'
FROM `stats`
WHERE 1
Note: There are other SO questions like Select most common value from a field in MySQL that ask how to calculate mode. This question is about using it exactly like AVG() in a function.