简体   繁体   English

"如何在我的 SQL 查询中使用 FIND_IN_SET 和 sum 列"

[英]How to use FIND_IN_SET and sum column in my SQL query

Can anyone help me?谁能帮我? I have a table result like this:我有一个这样的表格结果:

id_user id_user score分数 type类型
001 001 30 30 play
001 001 40 40 play
001 001 30 30 redeem赎回
002 002 20 20 play
002 002 30 30 redeem赎回

I want to sum column score group by id_user base on type 'play' and after that I want show ranking using find_in_set.我想根据 id_user 基于类型“play”对列得分组求和,然后我想使用 find_in_set 显示排名。 Like this is the result of the table that I want to display:就像这是我要显示的表格的结果:

id_user id_user total全部的 rank
001 001 70 70 1 1
002 002 20 20 2 2

Previously I used the rank() function in mysql Ver 10.4, but it does not work in MySQL ver 15.1.以前我在 mysql Ver 10.4 中使用了 rank() 函数,但它在 MySQL 15.1 中不起作用。 This is my previous query:这是我之前的查询:

SELECT id_user,  SUM(score) AS total,
       RANK() OVER (ORDER BY total DESC) AS rank
FROM result
WHERE type='play'
GROUP BY id_user

I have made some changes in your query.我对您的查询进行了一些更改。 It's working now.它现在正在工作。 Instead of column alias total SUM(score) needs to be used in order by clause of Rank() function's over().代替列别名total SUM(score) 需要按 Rank() 函数的 over() 子句的顺序使用。 And since Rank is a reserve word I used rnk instead.由于Rank是一个保留词,我使用rnk代替。

DB-Fiddle: DB-小提琴:

 create table result (id_user varchar(5), score int, type varchar(20));
 insert into result values('001',30 ,'play');
 insert into result values('001',40 ,'play');
 insert into result values('001',30 ,'redeem');
 insert into result values('002',20 ,'play');
 insert into result values('002',30 ',redeem');

Query:询问:

 select id_user,  SUM(score) AS total, RANK() OVER (ORDER BY SUM(score) DESC) AS rnk FROM result where type='play' GROUP BY id_user

Output:输出:

id_user id_user total全部的 rnk rnk
001 001 70 70 1 1
002 002 20 20 2 2

db<>fiddle here db<> 在这里摆弄

If your MySQL version doesn't support rank() you can use subquery to achieve same result:如果您的 MySQL 版本不支持 rank() 您可以使用子查询来获得相同的结果:

Query: select id_user, SUM(score) AS total, coalesce((select count(distinct id_user) from result r2 where type='play' group by id_user having sum(r2.score)>sum(r.score) ),0)+1 AS rnk FROM result r where type='play' GROUP BY id_user查询: select id_user, SUM(score) AS total, coalesce((select count(distinct id_user) from result r2 where type='play' group by id_user with sum(r2.score)>sum(r.score) ),0 )+1 AS rnk FROM result r where type='play' GROUP BY id_user

Output:输出:

id_user id_user total全部的 rnk rnk
001 001 70 70 1 1
002 002 20 20 2 2

db<>fiddle here db<> 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM