我想找到不同的方法来解决我遇到的现实生活问题:想象一下进行一场竞赛或游戏,用户在此期间收集积分。您必须构建一个查询来显示具有最佳“n”分数的用户列表。

我正在举一个例子来澄清。假设这是 Users 表,其中包含获得的积分:

UserId - Points
1      - 100
2      -  75
3      -  50
4      -  50
5      -  50
6      -  25

如果我想要前 3 名的分数,结果将是:

UserId - Points
1      - 100
2      -  75
3      -  50
4      -  50
5      -  50

这可以根据需要在视图或存储过程中实现。我的目标数据库是Sql Server。实际上我解决了这个问题,但我认为有不同的方法来获得结果......比我的更快或更有效。

有帮助吗?

解决方案

未经测试,但应该有效:

select * from users where points in
(select distinct top 3 points from users order by points desc)

其他提示

这是一个可行的方法 - 我不知道它是否更有效,它是 SQL Server 2005+

with scores as (
    select 1 userid, 100 points
    union select 2, 75
    union select 3, 50
    union select 4, 50
    union select 5, 50
    union select 6, 25
),
results as (
    select userid, points, RANK() over (order by points desc) as ranking 
    from scores
)
select userid, points, ranking
from results
where ranking <= 3

显然,第一个“with”是设置值,因此您可以测试第二个“with”,以及最终的选择工作 - 如果您正在查询现有表,则可以从“with results as...”开始。

怎么样:

select top 3 with ties points 
from scores
order by points desc

不确定“with ties”是否适用于其他 SQL Server。

在 SQL Server 2005 及更高版本上,您可以将“top”数字作为 int 参数传递:

select top (@n) with ties points 
from scores
order by points desc

实际上,对 WHERE IN 进行修改,使用 INNER JOIN 会快得多。

SELECT 
   userid, points 
FROM users u
INNER JOIN 
(
   SELECT DISTINCT TOP N 
      points 
   FROM users 
   ORDER BY points DESC
) AS p ON p.points = u.points

@bosnic,我认为这不会按要求工作,我对 MS SQL 不太熟悉,但我希望它只返回 3 行,并忽略 3 个用户并列第三的事实。

像这样的东西应该有效:

select userid, points 
   from scores 
   where points in (select top 3 points 
                       from scores 
                       order by points desc) 
   order by points desc

@罗布#37760:

select top N points from users order by points desc

如果 N 为 3,此查询将仅选择 3 行,请参阅问题。“Top 3”应返回 5 行。

@Espo 感谢您的现实检查 - 添加了子选择来纠正这一点。

我认为最简单的回应是:

select userid, points from users
where points in (select distinct top N points from users order by points desc) 

如果您想将其放入以 N 作为参数的存储过程中,那么您要么必须将 SQL 读入变量然后执行它,要么执行行计数技巧:

declare @SQL nvarchar(2000)
set @SQL = "select userID, points from users "
set @SQL = @SQL + " where points in (select distinct top " + @N
set @SQL = @SQL + " points from users order by points desc)"

execute @SQL

或者

SELECT  UserID, Points
FROM     (SELECT  ROW_NUMBER() OVER (ORDER BY points DESC)
         AS Row, UserID, Points FROM Users)
        AS usersWithPoints
WHERE  Row between 0 and @N

这两个示例都假设 SQL Server 并且尚未经过测试。

@马特·汉密尔顿

您的答案适用于上面的示例,但如果数据集为 100、75、75、50、50(仅返回 3 行),则答案将不起作用。TOP WITH TIES 仅包含返回的最后一行的领带...

Crucible 得到了它(假设 SQL 2005 是一个选项)。

嘿,我发现所有其他答案很长,效率低下,我的答案将是:

select * from users order by points desc limit 0,5

这将呈现前 5 点

尝试这个

select top N points from users order by points desc
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top