Skip to content
Advertisement

SQL comparing column changes the last X hours

I have a table containing log entries that looks like this:

id | name     | level |  timestamp
5  | ironman  | 35    |  2019-01-06 11:37:40
6  | ironman  | 35    |  2019-01-06 11:38:40
7  | ironman  | 36    |  2019-01-06 11:39:40
8  | superman | 25    |  2019-01-06 11:39:49

I need help making a query that returns a list of levels gained the last X hours for each character, preferably sorted by amount gained. So by this example my wanted result is this

id  |  name    |  gained  |  timestamp
7   | ironman  |  1       |  2019-01-06 11:37:40
8   | superman |  0       |  2019-01-06 11:37:40

Advertisement

Answer

Try an aggregate query that compares the MIN and MAX level of each character :

SELECT 
    name,
    MAX(level) - MIN(level) as gained,
    MIN(timestamp)
FROM mytable
WHERE timestamp > NOW() - INTERVAL 1 HOUR
GROUP BY 
    name
ORDER BY 
    gained desc

NB : this assumes that the level of a character may only increase. If the level of a character decreases, it will still appear as a gain.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement