英文:
Ranking players in SQL database will return always 1 when where id_user is used
问题
我基本上有一个名为"race"的表,包括"id_race"、"id_user"以及用户预测的列,如"pole_position"、"1st"、"2nd"、"3rd"和"fastest_lap"。除了这些列,每个预测列还有一个控制列,如"PPC"、"1eC"、"2eC"、"3eC"和"srC"。这些控制列随后会与"result"表进行比较。然后,"race"中的控制列将因正确的预测而获得积分。
我想对每个用户的这些结果进行累加,然后对每个用户进行排名。我想在玩家的用户页面上显示该排名。我已经为我的SQL查询编写了一个可以正常工作的查询,它会给我一个带有排名列的列表。
然而,当我添加了"where id_user"时,它总是获得第一名。是否有人有任何想法,可以解决这个问题,以及如何在我的排名查询中添加"where"条件?
我已经尝试过筛选。此外,我也尝试使用"Row_number"函数。但它总是返回1,因为在筛选后只有一个用户。我无法筛选出正确的位置。所以请帮帮我!
英文:
I basically have a table "race" with columns for "id_race", "id_user" and columns for user predictions "pole_position", "1st", "2nd", "3rd" and "fastest_lap". In addition to those columns, each prediction column also has a control column such as "PPC", "1eC", "2eC", "3eC" and "srC". Those control columns are then compared by a query against a "result" table. Then the control columns in race are awarded points for a correct prediction.
I want to add up those results per user and then rank them per user. I want to show that rank on the player's user page. I have a query for my SQL which works fine in itself and gives me a list with rank column.
SELECT
@rownum := @rownum +1 AS rank,
total,
id_user
FROM
(SELECT
SUM(PPC + 1eC + 2eC + 3eC + srC ) AS total,
id_user
FROM
race
GROUP BY
id_user
ORDER BY
total DESC) T,
(SELECT @rownum := 0) a;
Output of rank query:
However when I add the where id_user
it always gets the first rank. Does anyone have an idea if this can be solved and how I could achieve it to add where to my rank query?
I've already tried filtering. In addition, I have tried to use the Row_number
function. It also always gives a result of 1 because only 1 user remains after filtering. I am unable to filter out the correct position. So please help!
答案1
得分: 0
创建一个视图以提取正确的排名。一旦使用WHERE
子句,您将根据人口而不是子集获得排名。
请在fiddle上找到一个示意答案,其中使用了CTE
和ROW
函数。示意代码如下:
WITH sum_cte AS (
SELECT ROW_NUMBER() OVER(ORDER BY SUM(PPC + 1EC + 2eC + 3eC + srC) DESC) AS Row,
id_user,
SUM(PPC + 1EC + 2eC + 3eC + srC) AS total_sum
FROM race
GROUP BY id_user)
SELECT Row, id_user, total_sum
FROM sum_cte
WHERE id_user = 1
用户1的第二分数将以排名2显示。
英文:
You have to create a view to extracting the correct rank. Once you use WHERE
clause, you will get the rank based on the population rather that the subset.
Please find an indicative answer on fiddle where a CTE
and ROW
function are used. The indicative code is:
WITH sum_cte AS (
SELECT ROW_NUMBER() OVER(ORDER BY SUM(PPC + 1EC + 2eC + 3eC + srC) DESC) AS Row,
id_user,
SUM(PPC + 1EC + 2eC + 3eC + srC) AS total_sum
FROM race
GROUP BY id_user)
SELECT Row, id_user, total_sum
FROM sum_cte
WHERE id_user = 1
User 1 with the second score will appear with a row valuation 2.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论