Sample Header Ad - 728x90

Last cell value in a grouped by query

1 vote
3 answers
74 views

I have a table related to game results with more than 300 000 records, where each row keeps player attack. This is simplified table example. I keep an attack id, date, when attack was done, unique player id, player name (changeable by player), and result (bool value, victory or defeat). | attack_id | date | player_id | player_name | result | | -------- | -------------- | -------------- | -------------- |-------------- | | 1| 2024-03-09 00:00:00 | 1 | cat | 1 | 2| 2024-03-10 00:00:00| 1 | panda | 1 | 3| 2024-03-11 00:00:00| 2 | dog | 0 | 4| 2024-03-12 00:00:00| 3 | wolf | 1 I want to show 10 best attack players and my query looks like this: SELECT player_id as id, player_name as name, count(attack_id) as attacks, sum(result) as victory, ( count(attack_id) - sum(result) ) as defeat, ( sum(result) - ( count(attack_id) - sum(result) ) ) as difference FROM my_table_name GROUP BY player_id ORDER BY difference DESC LIMIT 10 Query calculates players' victories, defeats and difference between victories and defeats. The issue here related to player name. Player can change a name after some attacks, but this query returns the first player_name (related to player_id), not the last one (current). Result of this query (according to my example, instead of cat, should be panda, because it was the last player attack name): | id | name | attacks | victory | defeat | difference | | -------- | -------------- | -------------- | -------------- |-------------- |-------------- | | 1| cat | 2 | 2| 0| 2 | | 3| wolf| 1 | 1| 0| 1 | | 2| dog | 1 | 0| 1| -1 | How can I solve this issue?
Asked by anton (117 rep)
Mar 14, 2024, 03:11 PM
Last activity: Mar 15, 2024, 02:51 PM