Rank users in mysql by their total points across multiple rows - mysql

I have very much similar kind of requirement as described in this question.
Rank users in mysql by their points
The only difference is in my data. The above problem has the data where table has only row per student. But in my case there may be a possibility that table contains multiple rows for a single student like this
Student 1 points 80
Student 2 points 77.5
Student 2 points 4.5
Student 3 points 77
Student 4 points 77
So now rank should be calculated based on the SUM of points (total) that user has. So in this case result would be.
Student 2 Rank 1 with 82 points
Student 1 Rank 2 with 80 points
Student 3 Rank 3 with 77 points
Student 4 Rank 3 with 77 points
SQL Fiddle for data
I tried couple of things with the solution of above question but couldn't get the result. Any help would be appreciated.

Using the same query in my previous answer just change the table student for a subquery to combine all records of every student
change [student er] for
(SELECT `id`, SUM(`points`) as `points`
FROM students
GROUP BY `id`) er
SQL DEMO
select er.*,
(#rank := if(#points = points,
#rank,
if(#points := points,
#rank + 1,
#rank + 1
)
)
) as ranking
from (SELECT `id`, SUM(`points`) as `points`
FROM students
GROUP BY `id`) er cross join
(select #rank := 0, #points := -1) params
order by points desc;
OUTPUT
| id | points | ranking |
|----|--------|---------|
| 5 | 91 | 1 |
| 6 | 81 | 2 |
| 1 | 80 | 3 |
| 2 | 78 | 4 |
| 3 | 78 | 4 |
| 4 | 77 | 5 |
| 7 | 66 | 6 |
| 8 | 15 | 7 |

Try this:
select id, points, #row := ifnull(#row, 0) + diff rank
from (select *, ifnull(#prev, 0) != points diff, #prev := points
from (select id, sum(points) points
from students
group by 1
order by 2 desc) x) y
See SQLFiddle

EDITED:
(This should work)
SELECT I.Id, I.Points, Rk.Rank
FROM
(SELECT Id, Points, #Rk := #Rk+1 As Rank
FROM (SELECT id, SUM(points) AS Points
FROM students
GROUP BY id
ORDER BY Points DESC) As T,
(SELECT #Rk := 0) AS Rk) As I
INNER JOIN
(SELECT *
FROM (
SELECT Id, Points, #Rk2 := #Rk2+1 As Rank
FROM (SELECT id, SUM(points) AS Points
FROM students
GROUP BY id
ORDER BY Points DESC) As T1,
(SELECT #Rk2 := 0) AS Rk) AS T2
GROUP BY Points) As Rk
USING(Points)
The output will be:
| Id | Points | Rank |
|----|--------|---------|
| 5 | 91 | 1 |
| 6 | 81 | 2 |
| 1 | 80 | 3 |
| 2 | 78 | 4 |
| 3 | 78 | 4 |
| 4 | 77 | 6 |
| 7 | 66 | 7 |
| 8 | 15 | 8 |
After two Ids in 4th position you'll get the 6th position because 5 Ids are before of the 6th.

Related

How to select all enteties grouped by common propertie without loop?

Is there any way to fatch all entities from table grouped by common property while loop?
Table storage looks like this
id | product_id | category_id
-----------+-----------------------+--------------------------
1 | 1 | 15
2 | 2 | 17
3 | 3 | 18
4 | 4 | 17
5 | 5 | 15
6 | 6 | 17
7 | 7 | 18
and final result supposed to look like this
id | product_id | category_id
-----------+-----------------------+--------------------------
1 | 1 | 15
2 | 2 | 17
3 | 3 | 18
4 | 5 | 15
5 | 4 | 17
6 | 7 | 18
7 | 6 | 15
What i want is this:
Select each record grouped by category id. It means, if table size is 3200, i need to select all of 3200 records grouped by category id in ASC order
You seem to want the values interleaved. You can use row_number() in the order by:
select s.*
from storage s
order by row_number() over (partition by storage_id order by id),
storage_id;
Here is a db<>fiddle.
EDIT:
In older versions of MySQL, you can assign a sequential number within each group using variables and then use that for ordering:
select s.*
from (select s.*,
(#rn := if(#sid = storage_id, #rn + 1,
if(#sid := storage_id, 1, 1)
)
) as seqnum
from (select s.* from storage s order by storage_id, id) s cross join
(select #rn := 0, #sid := -1) params
) s
order by seqnum, id;
The SQL Fiddle has both methods.

Get 10 latest records per category even some has less then 10

This is example of my table :
+-----+-----+------------+--------+-------------+--------------+
| LID | AID | Created | TypeID | PaymentDate | PaymentValue |
+-----+-----+------------+--------+-------------+--------------+
| 1 | 529 | 2017-05-12 | 1 | 2017-05-12 | 100 |
+-----+-----+------------+--------+-------------+--------------+
| 2 | 529 | 2018-04-10 | 4 | 2018-04-10 | 200 |
+-----+-----+------------+--------+-------------+--------------+
| 3 | 441 | 2014-01-23 | 3 | 2014-01-23 | 300 |
+-----+-----+------------+--------+-------------+--------------+
| 4 | 324 | 2017-09-14 | 1 | 2017-09-14 | 400 |
+-----+-----+------------+--------+-------------+--------------+
| 5 | 111 | 2018-05-12 | 0 | 2018-05-12 | 340 |
+-----+-----+------------+--------+-------------+--------------+
| 6 | 529 | 2018-05-12 | 1 | 2018-05-12 | 100 |
+-----+-----+------------+--------+-------------+--------------+
| 7 | 529 | 2018-06-12 | 1 | 2018-05-12 | 100 |
+-----+-----+------------+--------+-------------+--------------+
| 8 | 529 | 2018-07-12 | 1 | 2018-05-12 | 100 |
+-----+-----+------------+--------+-------------+--------------+
| 9 | 529 | 2018-08-12 | 1 | 2018-05-12 | 100 |
+-----+-----+------------+--------+-------------+--------------+
| 10 | 529 | 2018-09-12 | 1 | 2018-05-12 | 100 |
+-----+-----+------------+--------+-------------+--------------+
| 11 | 529 | 2018-01-12 | 1 | 2018-05-12 | 100 |
+-----+-----+------------+--------+-------------+--------------+
| 12 | 529 | 2018-05-14 | 1 | 2018-05-12 | 100 |
+-----+-----+------------+--------+-------------+--------------+
| 13 | 529 | 2018-05-21 | 1 | 2018-05-12 | 100 |
+-----+-----+------------+--------+-------------+--------------+
| 14 | 529 | 2018-03-12 | 1 | 2018-05-12 | 100 |
+-----+-----+------------+--------+-------------+--------------+
Here another table
+-----+-------+
| ID |caption|
+-----+-------+
| 0 | bad |
+-----+-------+
| 1 | good |
+-----+-------+
I need to get 10 latest records per AID. If there less than 10 records for some AID anyway i need to get ten rows and put "No payment date" into PaymentDate and Created fields, Null into TypeID and 0 into PaymentValue. I can get 10 or less latest records with
select *
from (select *,
(#rn := if(#c = AID, #rn + 1,
if(#c := AID, 1, 1)
)
) as rn
from history cross join
(select #rn := 0, #c := -1) params
order by AID, Created desc
) t
having rn <= 10;
But i dont know how force mysql to output 10 rows for each AID. Help me please.
Result should be in a form
AID,TypeId,Created,Caption
I have done it.
This query needs to create a row of 10 records to combine with distinct AID valies in the table. I was able to show the result for Amount and Create date and will leave it to you to continue since you will get the idea.
The critical part is to build a table with 10 rows times distinct AID so about 40 rows in table r. Then do a left join to table t which is similar to what you have done. Table t gets a rank of at most 10 records. Any missing rank up to 10 recs will be filled by table r. Coalesce will assign the default values such as 0 fro amount and 'no create date' for date.
http://sqlfiddle.com/#!9/855c21/2
SELECT coalesce(r.aid, t.aid) as aid,
coalesce(t.paymentvalue, 0) as paymentvalue,
coalesce(cast(t.created as char), 'no create date') as created
FROM (select * from (
select 1 as rw union
select 2 union select 3
union select 4 union select 5
union select 6 union select 7
union select 8 union select 9
union select 10) u
cross join (select distinct aid
from history) h
) as r
LEFT JOIN (
SELECT a.aid, a.paymentvalue,
a.created, count(*) rn
FROM history a
JOIN history b
ON a.aid = b.aid
AND a.created <= b.created
GROUP BY a.aid, a.created
HAVING COUNT(*) <= 10) t
on r.rw=t.rn and r.aid=t.aid
order by aid, created;
I have added RIGHT JOIN to bring in the null rows to top up to 10 (or n) rows per AID. Initially I use SELECT 1 UNION SELECT 2 ... to generate the 10 rows. In order to make it easier to increase the number of rows (say 100), I am trying this idea of generate_series equivalent for mysql. In order for this to work, the number of rows in history table must be equal to greater than the number of rows required per AID.
select t1.lid
,t2.aid
,coalesce(t1.created, "no created date") as created
,t1.typeID
,coalesce(t1.paymentdate, "no payment date") as paymentDate
,coalesce(t1.paymentvalue, 0) as paymentValue
,t2.rn
from
(
select *,
(#rn := if(#c = AID, #rn + 1,
if(#c := AID, 1, 1)
)
) as rn
from history cross join
(select #rn := 0, #c := -1) params
order by AID, Created desc
) t1
right join
( select *
from (select distinct aid from history ) h1
cross join
(select rn -- generate table with n rows numbered from 1 to n
from
(select
#num:= 0) init
cross join
(select #num := #num +1 rn
from history ) t -- assume history has at least 10 rows
limit
10 ) h2 -- n = 10; change it to the number of rows per aid required
) t2
on t1.aid = t2.aid and t1.rn = t2.rn
order by t2.aid, t2.rn

Sum or count only few/limited row from a table

I have a student mark table where i putted student marks by subject. I wanted to take sum of maximum 3 subjects for each student. And also wanted to see subject count or how many subjects mark entry exist on this table group by a student. This is my table structure.
students
----------------------
id | name | roll
----------------------
1 | Rahim | 201
2 | Kalas | 203
----------------------
student_marks
--------------------------------
id | student_id | subject | mark
--------------------------------
1 | 1 | A | 10
2 | 1 | B | 5
3 | 1 | C | 10
4 | 1 | D | 5
5 | 2 | A | 10
6 | 2 | B | 10
--------------------------------
my_expected_table
----------------------------------
student_id | student_name | sum
----------------------------------
1 | Rahim | 25
2 | Kalas | 20
----------------------------------
I am trying but can't understand how would i give limit on join table my sample query here
SELECT students.id as student_id,
students.name as student_name,
sum(student_marks.mark) as sum
From students
inner join student_marks on student_marks.student_id = students.id
Group by student_marks.student_id
the query output you know, it will show sum of all row. but i want like previous table "my_expected_table"
----------------------------------
student_id | student_name | sum
----------------------------------
1 | Rahim | 30
2 | Kalas | 20
----------------------------------
This is painful to do in MySQL. The best way uses variables:
select sm.student_id, count(*) as num_marks,
sum(case when rn <= 3 then mark end) as random_3_sum
from (select sm.*,
(#rn := if(#s = student_id, #rn + 1,
if(#s := student_id, 1, 1)
)
) as rn
from student_marks sm cross join
(select #rn := 0, #s := -1) params
order by student_id, id
) sm
group by sm.student_id;
Notes:
I didn't both with the join to the student table, that is obvious to add.
This defines 3 marks as "the 3 marks on the rows with the lowest id". This is determined by the second order by key.

calculating ranking in SQL

I have a table which has float score, and I want to rank them from largest to smallest, if the same score, same ranking. I am using MySQL/MySQL Workbench, and any good ideas are appreciated.
Here is a sample input and output,
+----+-------+
| Id | Score |
+----+-------+
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
+----+-------+
+-------+------+
| Score | Rank |
+-------+------+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
+-------+------+
Tried the following query, but not working since it does not handle duplicate,
SELECT id, score,
#curRank := #curRank + 1 AS rank
FROM TestRank tr, (SELECT #curRank := 0) r
ORDER BY score desc;
In this above query, user 3 and user 5 have the same score value 4, but ranked differently.
I also tried the following query to just rank score itself, and it returns very weird results,
set #curRank := 0;
SELECT distinct score, #curRank := #curRank+1 as rank
FROM TestRank tr
ORDER BY score desc;
thanks in advance,
Lin
Check out this fiddle : http://sqlfiddle.com/#!9/17a49/3
Here's the query that will work for you:
SELECT
s.score, scores_and_ranks.rank
FROM
scores s
JOIN
(
SELECT
score_primary.score, COUNT(DISTINCT score_higher.score) + 1 AS rank
FROM
scores score_primary
LEFT JOIN scores score_higher ON score_higher.score > score_primary.score
GROUP BY score_primary.score
) scores_and_ranks
ON s.score = scores_and_ranks.score
ORDER BY rank ASC
In the "scores_and_ranks" inner query, we total up the number of distinct scores that are better than the current score. The top score will have zero, so we add 1 to get the rank value you want.
The reason we have to join to that table (using table "s") is to make sure the duplicate score values (two rows with score=4, for example) are shown in distinct rows.
You can do this by "remembering" the previous score:
SELECT id, score,
(#curRank := if(#s = score, #curRank + 1,
if(#s := score, 1, 1)
)
) as rank
FROM TestRank tr CROSS JOIN
(SELECT #curRank := 0, #s := -1) r
ORDER BY score desc;

mySQL Ranking (and draws)

Next weekend we're having a competition with 3 qualifications a semifinal and a final. Only the best 15 participants could compete in the semifinal. Only the best 6 compete in the Finals.
in the qualifications you get a score from 0 to 100 for each qualification
I'm looking to find a way to select the contesters for the semi-final. This should be based on (rank of qualification1) * (rank of qualification2) * (rank of qualification3)
so i need something like:
select id, name, ((.... as RANK_OF_SCORE_1) * (.. as RANK_OF_SCORE_2) * (... as RANK_OF_SCORE_3)) as qualification_score from participants order by qualification_score desc limit 15
but of course this is not valid mySQL.
Besides this problem if tho contesters have the same score, they should be both included in the semi-finals even if this exceeds the maximum of 15.
For the finals, we would like to select the best 6 of the semi-final scores. If 2 scores are the same we would like to select on the qualifications..
option 1 : use postgres, which support windowing functions (namely RANK() and DENSE_RANK())
SELECT user_id, score, rank() over (order by score desc) from scores;
Time : 0.0014 s
option 2 : use a self- join : the rank of a user with score X is (1 +the count(*) of users with score less than X) ; this is likely to be pretty slow
CREATE TABLE scores( user_id INT PRIMARY KEY, score INT, KEY(score) );
INSERT INTO scores SELECT id, rand()*100 FROM serie LIMIT 1000;
SELECT a.user_id, a.score, 1+count(b.user_id) AS rank
FROM scores a
LEFT JOIN scores b ON (b.score>a.score)
GROUP BY user_id ORDER BY rank;
+---------+-------+------+
| user_id | score | rank |
+---------+-------+------+
| 381 | 100 | 1 |
| 777 | 100 | 1 |
| 586 | 100 | 1 |
| 907 | 100 | 1 |
| 790 | 100 | 1 |
| 253 | 99 | 6 |
| 393 | 99 | 6 |
| 429 | 99 | 6 |
| 376 | 99 | 6 |
| 857 | 99 | 6 |
| 293 | 99 | 6 |
| 156 | 99 | 6 |
| 167 | 98 | 13 |
| 594 | 98 | 13 |
| 690 | 98 | 13 |
| 510 | 98 | 13 |
| 436 | 98 | 13 |
| 671 | 98 | 13 |
time 0.7s
option 3 :
SET #rownum = 0;
SELECT a.user_id, a.score, b.r FROM
scores a
JOIN (
SELECT score, min(r) AS r FROM (
SELECT user_id, score, #rownum:=#rownum+1 AS r
FROM scores ORDER BY score DESC
) foo GROUP BY score
) b USING (score)
ORDER BY r;
time : 0.0014 s
EDIT
SET #rownum1 = 0;
SET #rownum2 = 0;
SET #rownum3 = 0;
SELECT s.*, s1.r, s2.r, s3.r FROM
scores s
JOIN
(
SELECT score_1, min(r) AS r FROM (
SELECT score_1, #rownum1:=#rownum1+1 AS r
FROM scores ORDER BY score_1 DESC
) foo GROUP BY score_1
) s1 USING (score_1) JOIN (
SELECT score_2, min(r) AS r FROM (
SELECT score_2, #rownum2:=#rownum2+1 AS r
FROM scores ORDER BY score_2 DESC
) foo GROUP BY score_2
) s2 USING (score_2) JOIN (
SELECT score_3, min(r) AS r FROM (
SELECT score_3, #rownum3:=#rownum3+1 AS r
FROM scores ORDER BY score_3 DESC
) foo GROUP BY score_3
) s3 USING (score_3)
ORDER BY s1.r * s2.r * s3.r;