Sql server 从hiscore表创建hiscore列表
我想创建他的核心列表,但我很难做到这一点。这是我的hiscore表,对于每一场比赛,我都会将用户得分写入该表 这是我的hiscore表的外观:Sql server 从hiscore表创建hiscore列表,sql-server,Sql Server,我想创建他的核心列表,但我很难做到这一点。这是我的hiscore表,对于每一场比赛,我都会将用户得分写入该表 这是我的hiscore表的外观: id user_id user_name score entry_date ----------------------------------------------------------- 1 1 tom 500 2012-06-05 14:30:00 2 1
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个最大分数,但我必须确保他们的分数相同,然后我应该获得第一个输入的分数(基于entry\u 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
更新:关于分数和问题
关于分数总和,我需要在查询原始hiscore表时返回此值的查询:
user_id user_name score
--------------------------------
1 Tom 1000
2 Jim 800
3 Tony 650
如果有两个用户的得分总和相同,排名较好的用户就是其核心表中条目较少的用户。编辑:第一个查询是谎言,不起作用!:),假设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)
这将为您提供按“分数”之和降序排列的分数,然后按条目数升序排列的分数,这将为您提供所需的分数
;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
结果谢谢,就是这样。如果我有相同的表,但我不是在寻找他的核心,而是每个用户的得分总和,那么您可以编写SQL查询吗。所以我想得到最佳分数总和的列表。如果你知道我的意思的话。我已经更新了我的答案,以找出每个用户的最佳分数。我刚刚更新了关于分数总和列表的问题。如果你能帮我的话,我会非常感激的。这很有效,因为它和我的答案完全一样,只是顺序不同:D
;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