'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 | score | type |
|---|---|---|
| 001 | 30 | play |
| 001 | 40 | play |
| 001 | 30 | redeem |
| 002 | 20 | play |
| 002 | 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. Like this is the result of the table that I want to display:
| id_user | total | rank |
|---|---|---|
| 001 | 70 | 1 |
| 002 | 20 | 2 |
Previously I used the rank() function in MySQL version 10.4, but it does not work in MySQL version 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
Solution 1:[1]
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(). And since Rank is a reserve word I used rnk instead.
DB-Fiddle:
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 | total | rnk |
|---|---|---|
| 001 | 70 | 1 |
| 002 | 20 | 2 |
db<>fiddle here
If your MySQL version doesn't support rank() you can use subquery to achieve same result:
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
Output:
| id_user | total | rnk |
|---|---|---|
| 001 | 70 | 1 |
| 002 | 20 | 2 |
db<>fiddle here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
