优化查询以在 MS SQL Server 中创建排名

Optimize a query for creating a ranking in MS SQL Server(优化查询以在 MS SQL Server 中创建排名)
本文介绍了优化查询以在 MS SQL Server 中创建排名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在创建一个应用程序,用户可以在其中进行锻炼.他们通过应用程序传递结果,这些结果存储在 SQL Server 数据库中.结果以这种方式保存在 SQL Server 表中:

I'm creating an application where users do workouts. They pass on their results via an app, and these results are stored in an SQL Server database. Results are saved in this way in a SQL Server table:

我想编写一个查询,根据每个用户的最佳分数创建一个排名.这是我目前所拥有的:

I want to write a query to create a ranking based on the best score of each user. This is what I have so far:

SELECT id, 
       workout_id, 
       level_id, 
       a.user_id, 
       total_time, 
       score, 
       datetime_added
FROM nodefit_rankings_fitness as a INNER JOIN
    (
     SELECT user_id, 
            MAX(score) AS MAXSCORE 
     FROM nodefit_rankings_fitness 
     GROUP BY user_id
    ) AS lookup
ON  lookup.user_id = a.user_id
    AND 
    lookup.MAXSCORE  =  a.score
ORDER BY score DESC, 
         datetime_added DESC

这会产生这个排名:

问题是,如果用户多次达到相同的最高分,他将多次出现在排名中.必须调整查询,以便当用户多次获得相同的最高分数时,排名中仅显示最后一次尝试的结果(基于 datetime_ added 列).

The problem is that if a user has achieved the same maximum score a number of times, he will appear multiple times in the ranking. The query must be adjusted so that when a user has the same maximum score a few times, only the result of the last attempt (based on the datetime_added column) is displayed in the rankings.

不幸的是,我自己找不到解决方案.我们当然感谢您的帮助.

Unfortunately, I cannot find a solution myself. Help is certainly appreciated.

推荐答案

如果你关心性能,你也应该尝试关联子查询:

If you care about performance, you should also try a correlated subquery:

SELECT id, workout_id, level_id, a.user_id, total_time, score, datetime_added
FROM nodefit_rankings_fitness nrf
WHERE nrf.id = (SELECT TOP (1) nrf2.id
                FROM nodefit_rankings_fitness nrf2
                WHERE nrf2.user_id = nrf.user_id
                ORDER BY nrf2.score DESC
               )
ORDER BY score DESC, datetime_added DESC;

特别是,这可以利用 nodefit_rankings_fitness(user_id, score desc, id) 上的索引.

In particular, this can take advantage of an index on nodefit_rankings_fitness(user_id, score desc, id).

这篇关于优化查询以在 MS SQL Server 中创建排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)