0

我想创建他的核心列表,但我做不到。这是我的 hiscore 表,对于每场比赛,我都会将用户得分写入此表。

这是我的 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 查询,但通过该查询,我得到了 hiscore 列表,但它不是按 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

如果有两个用户的得分和相同,则排名较高的用户是 hiscore 表中条目较少的用户。

4

2 回答 2

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

结果在SqlFiddle

于 2012-07-10T15:31:02.113 回答
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) 

这将为您提供按“分数”总和降序排序的分数,然后按条目数升序排序,这应该会给你你想要的

于 2012-07-10T15:09:56.143 回答