I want to create hiscore list, but I have trouble doing it. This is my hiscore table and for every game I write user score into this table.
This is how my hiscore table look like:
id user_id user_name score entry_date
-----------------------------------------------------------
1 1 tom 500 2012-06-05 14:30:00
2 1 tom 500 2012-06-05 10:25:00
3 2 jim 300 2012-06-05 09:20:00
4 2 jim 500 2012-06-05 09:22:00
5 3 tony 650 2012-06-05 15:45:00
I want to get first 3 MAX scores, but I have to make sure if they have same score then I should take score that is first entered (based on entry_date column)
The query returned should be something like this.
1. 3 tony 650 2012-06-05 15:45:00 <- hi have to be first, because he have top score
2. 2 jim 500 2012-06-05 09:22:00 <- jim have the same score as tom, but he make that score before tom did so he is in second place
3. 1 tom 500 2012-06-05 10:25:00 <- tom have 2 entries with the same score, but we only take the one with smallest date
This is SQL query that I wrote but with that query i am getting hiscore list but it’s not ordered by entry_date and I don’t have any idea how to solve this problem.
SELECT TOP 3
hiscore.user_id,
hiscore.user_name,
MAX(hiscore.score) AS max_score,
FROM
hiscore
GROUP BY
hiscore.user_id, hiscore.user_name
ORDER BY
max_score DESC
UPDATE: Regarding score sum question
Regarding score sum, I need query that will return this when querying original hiscore table:
user_id user_name score
--------------------------------
1 Tom 1000
2 Jim 800
3 Tony 650
And if there are two users with the same score sum, user with better rank is the one with less entries in hiscore table.
Edit: this first query is a lie and won’t work! :), assuming sql 2005+ use the second one
Just add EntryDate to your order by
Edit: ah I didn’t even see the group by – forget that, hang on a sec!
This one 😛
assuming SQL 2005+
Edit:
In order to get the best scores ordered by score and then by number of entries the query is a bit simpler:
This will give you the scores ordered by the sum of ‘score’ descending, and then ordered by number of entries ascending which should give you what you want