AlanPHP
AlanPHP

Reputation: 188

Find highest difference between two rows

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!".

Upvotes: 2

Views: 3224

Answers (1)

mathematical.coffee
mathematical.coffee

Reputation: 56905

This gets the maximum difference in energy per user, ignoring users with only a single record:

SELECT hoflevel.username, MAX(hoflevel.energy-h.energy) as maxDiff 
FROM hoflevel 
LEFT JOIN hoflevel h 
ON h.username=hoflevel.username AND hoflevel.energy>=h.energy
WHERE h.energy IS NOT NULL
GROUP BY hoflevel.username;

Basically, it joins hoflevel to itself on username which produces a table with username and every pair of energy values 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 energy each time (and so their maxDiff is 0) by changing the >= to a > in the join condition.

Upvotes: 5

Related Questions