I have a table that stores values each hour from a website based on 100 users. Each user is there each hour, but might have a higher/lower value.
I want to find the highest difference between the rows and output them.
mysql_query("SELECT `username`,`energy` FROM `hoflevel`");
I know I could loop through all the rows of each user and find the highest value, but that is too much code. I’m sure there is a way to figure out the biggest difference between two rows, grouped by the username. It doesn’t have to be only each hour. It would be like a “Alan set the record of 345,048 Energy at 5am yesterday!“.
This gets the maximum difference in
energyper user, ignoring users with only a single record:Basically, it joins
hoflevelto itself onusernamewhich produces a table withusernameand every pair ofenergyvalues for that user.Then it works out the maximum difference between energies grouped by
username.Note, you could further save some computation by ignoring users who may have multiple records in the database but the same
energyeach time (and so theirmaxDiffis 0) by changing the>=to a>in the join condition.