我想创建他的核心列表,但我很难做到。这是我的自己的桌面,我在每个游戏中都会将用户分数写入此表。
这是我的hiscore表的样子:
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
我想获得前3个MAX分数,但我必须确定他们是否有相同的分数然后我应该取得首次输入的分数(基于entry_date
列)
返回的查询应该是这样的。
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
这是我写的SQL查询,但是使用该查询我得到了他的核心列表,但它没有被entry_date排序,我也不知道如何解决这个问题。
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
关于得分总和,我需要在查询原始的hiscore表时返回此查询:
user_id user_name score
--------------------------------
1 Tom 1000
2 Jim 800
3 Tony 650
如果有两个用户具有相同的得分总和,那么排名较高的用户是其核心表中的条目较少的用户。
答案 0 :(得分:1)
试试这个:
;with cte as
(Select id ,userID,score,entry_date,row_number() over(partition by userID
order by score desc,entry_date) as row_num from Score
)
Select * from cte where row_num=1 ORDER BY Score DESC,entry_date
// sum of score for individual user
Select UserID,sum(Score) from Score
group by UserID
答案 1 :(得分:0)
修改:这第一个查询是谎言,不起作用! :),假设sql 2005+使用第二个
只需通过
将EntryDate添加到您的订单中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, entry_date DESC
编辑:啊我甚至没有看到小组 - 忘了那个,等一下!
这一个:P
SELECT * FROM (SELECT
hiscore.user_id,
hiscore.user_name,
hiscore.score,
hiscore.entry_date,
ROW_NUMBER() OVER (PARTITION BY User_id ORDER BY Score DESC, entry_date) as scoreNo
FROM
hiscore
) as highs WHERE ScoreNo = 1 ORDER BY Score DESC, entry_date
假设SQL 2005 +
编辑:
为了获得按分数排序的最佳分数,然后按条目数量排序,查询更简单:
SELECT user_id, user_name, SUM(score) as Score from hiscore
GROUP BY user_id, user_name
ORDER BY sum(score) DESC, count(score)
这将为您提供按“得分”降序总和排序的分数,然后按升序的数量排序,这应该可以为您提供所需的分数