How to compute ranks in mysql? - mysql

I have a table 'student_marks' with two columns 'student_id' and 'mark':
student_id | marks
-------------------
1 | 5
2 | 2
3 | 5
4 | 1
5 | 2
I need to compute the rank corresponding to the marks. The expected output for the above table is:
student_id | marks | rank
-------------------------
1 | 5 | 1
2 | 2 | 3
3 | 5 | 1
4 | 1 | 5
5 | 2 | 3
Since the two students with students_id 1 and 3 has highest mark 5, they are placed in rank 1. For students with marks 2, the rank is 3 as there are two students who has more marks then these guys.
How do we write queries to compute the ranks as shown above?

This should work although it's heavy on variables.
SELECT student_id, mark, rank FROM (
SELECT t.*,
#rownum := #rownum + 1 AS realRank,
#oldRank := IF(mark = #previous,#oldRank,#rownum) AS rank,
#previous := mark
FROM student_marks t,
(SELECT #rownum := 0) r,
(SELECT #previous := 100) g,
(SELECT #oldRank := 0) h
ORDER BY mark DESC
) as t
ORDER BY student_id;
Look at this fiddle: http://sqlfiddle.com/#!2/2c7e5/32/0

Related

How do you revert the cartesian product of two columns in SQL in order to get the columns before computing the cross join (cartesian product)?

Let's assume I have two columns: letters and numbers in a table called tbl;
letters numbers
a 1
b 2
c 3
d 4
Doing a cartesian product will lead to :
a 1
a 2
a 3
a 4
b 1
b 2
b 3
b 4
c 1
c 2
c 3
c 4
d 1
d 2
d 3
d 4
Write a query that reverts the cartesian product of these two columns back to the original table.
I tried multiple methods from using ROWNUM to selecting distinct values and joining them (which leads me back to the cartesian product)
SELECT DISTINCT *
FROM (SELECT DISTINCT NUMBERS
FROM TBL
ORDER BY NUMBERS) AS NB
JOIN (SELECT DISTINCT LETTERS
FROM TBL
ORDER BY LETTERS) AS LT1
which led me back to the cartesian product....
This is a version that works with 5.7.
SELECT `numbers`,`letters` FROM
(SELECT `numbers`,
#curRank := #curRank + 1 AS rank
FROM Table1 t, (SELECT #curRank := 0) r
GROUP By `numbers`
ORDER BY `numbers`) NB1
INNER JOIN
(SELECT `letters`,
#curRank1 := #curRank1 + 1 AS rank
FROM (
Select `letters` FROM Table1 t
GROUP By `letters`) t2, (SELECT #curRank1 := 0) r
ORDER BY `letters`) LT1 ON NB1.rank = LT1.rank;
https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=cc17c2cfeff049edc73e437e5e4fd892
As Raymond and Ankit pointed out you have to know which order have the letters and even the order of the numbers has to be defined prior or else you never get a correct answer.
Another way of writing this:
SELECT numbers
, letters
FROM
( SELECT DISTINCT numbers
, #curRank := #curRank + 1 rank
FROM Table1 t
, (SELECT #curRank := 0) r
ORDER
BY numbers
) NB1
JOIN
( SELECT letters
, #curRank1 := #curRank1 + 1 rank
FROM
( SELECT DISTINCT letters
FROM Table1 t
) t2
, (SELECT #curRank1 := 0) r
ORDER
BY letters
) LT1
ON NB1.rank = LT1.rank;
If you are sure that the order will never be destroyed and is deterministic, You can use dense_rank() analytic function to achieve it back -
SELECT LT1.LETTERS, NB.NUMBERS
FROM (SELECT DISTINCT NUMBERS
FROM TBL
ORDER BY NUMBERS) AS NB
JOIN (SELECT DISTINCT LETTERS, RN
FROM (SELECT LETTERS, DENSE_RANK() OVER (ORDER BY LETTERS) RN
FROM TBL
ORDER BY LETTERS) T) AS LT1
ON NB.NUMBERS = LT1.RN
Here is the fiddle
Perhaps this is oversimplifying the problem, but it should be seen that this, or some variation of it, would suffice...
SELECT * FROM my_table;
+---------+---------+
| letters | numbers |
+---------+---------+
| a | 1 |
| a | 2 |
| a | 3 |
| a | 4 |
| b | 1 |
| b | 2 |
| b | 3 |
| b | 4 |
| c | 1 |
| c | 2 |
| c | 3 |
| c | 4 |
| d | 1 |
| d | 2 |
| d | 3 |
| d | 4 |
+---------+---------+
16 rows in set (0.00 sec)
SELECT x.*
, #i:=#i+1 numbers
FROM
( SELECT DISTINCT letters
FROM my_table
) x
, (SELECT #i:=0) vars
ORDER
BY letters;
+---------+---------+
| letters | numbers |
+---------+---------+
| a | 1 |
| b | 2 |
| c | 3 |
| d | 4 |
+---------+---------+

Mysql Ranking within grouped results

I have read posts that answer how to rank results in mysql, but my question is how to assign ranks within a group
Let me explain with an example
Data:
sem_id | result_month
--------------------
1 |1313907325000
1 |1345529725000
2 |1329804925000
2 |1361427325000
3 |1377065725000
3 |1440137725000
What i am able to achieve with the below query:
SELECT #ss := #ss + 1 AS rank,
res.sm_id,
res.result_month
FROM (SELECT sm_id, result_month
FROM xx_table
GROUP BY sm_id,
result_month) AS res,(SELECT #ss := 0) AS ss;
Current results:
rank | sem_id | result_month
----------------------------
1 | 1 |1313907325000
2 | 1 |1345529725000
3 | 2 |1329804925000
4 | 2 |1361427325000
5 | 3 |1377065725000
6 | 3 |1440137725000
What I actually want :
rank | sem_id | result_month
----------------------------
1 | 1 |1345529725000
2 | 1 |1313907325000
1 | 2 |1361427325000
2 | 2 |1329804925000
1 | 3 |1440137725000
2 | 3 |1377065725000
In the above results things to observe is each group is ranked within itself and each group is ordered by result_month desc
Help me on how can i achieve the above results
Thanks in advance!
You're almost there, use another variable to compute group:
SELECT #ss := CASE WHEN #grp = sem_id THEN #ss + 1 ELSE 1 END AS rank, sem_id, result_month, #grp := sem_id
FROM (select * from xx_table ORDER BY sem_id, result_month DESC) m
CROSS JOIN (SELECT #ss := 0, #grp = null) ss
See demo here.

Mysql Select records from a table loop group by field

I have a table with products.
The table has a companyId field.
Let's describe it like this:
id --- companyId
1 | 2
2 | 3
3 | 4
4 | 2
5 | 3
6 | 1
7 | 4
I want to select all the records ordered by companyId but with the company id looping, as so:
id --- companyId
6 | 1
1 | 2
2 | 3
3 | 4
4 | 2
5 | 3
7 | 4
How can I achieve it?
You can achieve this using MySQL user defined variables
SELECT
t.id,
t.companyId
FROM
(
SELECT
*,
IF(#sameCompany = companyId , #rn := #rn + 1,
IF(#sameCompany := companyId, #rn := 1,#rn := 1)
) AS rn
FROM companytable
CROSS JOIN (SELECT #sameCompany := -1, #rn := 1) AS var
ORDER BY companyId
) AS t
ORDER BY t.rn , t.companyId
See Demo
Explanation:
First sort the data according to companyId so that the same company ids stick together.
Now take a walk along this sorted result and assign a sequentially increasing row number every time you see the same companyId otherwise assign 1 as row number.
Now name this sorted result (with row number) t.
Finally sort these data (t) according to ascending row number and ascending companyId.

Rank users in mysql by their points

I am trying to rank my students by their points that I've calculated before
but the problem is if students have same points they both should be in same rank
E.g
Student 1 has full points
Student 2 has full points
they both have to be rank as 1;
Here an example of my database
the query I am trying to do is (just for select then I can insert the values to my column)
SELECT a.points
count(b.points)+1 as rank
FROM examresults a left join examresults b on a.points>b.points
group by a.points;
Edit for being more clear:
Student 1 points 80
Student 2 points 77.5
Student 3 points 77.5
Student 4 points 77
their ranks should be like
Student 1 Rank 1
Student 2 Rank 2
Student 3 Rank 2
Student 4 Rank 3
my current query returns a values like
As it is missing the third rank. (because second rank has 2 values)
This is just a fix of Gordon solution using variables. The thing is your rank function isnt the way rank should work. (student 4 should be rank 4)
SQL Fiddle Demo You can add more student to improve the testing.
select er.*,
(#rank := if(#points = points,
#rank,
if(#points := points,
#rank + 1,
#rank + 1
)
)
) as ranking
from students er cross join
(select #rank := 0, #points := -1) params
order by points desc;
OUTPUT
| id | points | ranking |
|----|--------|---------|
| 1 | 80 | 1 |
| 2 | 78 | 2 |
| 3 | 78 | 2 |
| 4 | 77 | 3 |
| 5 | 66 | 4 |
| 6 | 66 | 4 |
| 7 | 66 | 4 |
| 8 | 15 | 5 |
You want a real rank, which is calculated by the ANSI standard rank() function. You can implement this in MySQL using this logic:
select er.*,
(select 1 + count(*)
from examresults er2
where er2.points > er.points
) as ranking
from exampleresults er;
For larger tables, you can do this with variables, but it is a rather awkward:
select er.*,
(#rank := if(#rn := #rn + 1 -- increment row number
if(#points = points, #rank, -- do not increment rank
if(#points := points, -- set #points
#rn, #rn -- otherwise use row number
)
)
)
) as ranking
from examresults er cross join
(select #rn := 0, #rank := 0, #points := -1) params
order by points desc;
this query achieve what do you want:
SELECT student_id , points, (select count(distinct(points))+1 as rank
from examresults internal
where internal.points > external.points order by points)
FROM examresults external
group by student_id

Top x rows and group by (again)

I know it's a frequent question but I just can't figure it out and the examples I found didn't helped. What I learned, the best strategy is to try to find the top and bottom values of the top range and then select the rest, but implementing is a bit tricky.
Example table:
id | title | group_id | votes
I'd like to get the top 3 voted rows from the table, for each group.
I'm expecting this result:
91 | hello1 | 1 | 10
28 | hello2 | 1 | 9
73 | hello3 | 1 | 8
84 | hello4 | 2 | 456
58 | hello5 | 2 | 11
56 | hello6 | 2 | 0
17 | hello7 | 3 | 50
78 | hello8 | 3 | 9
99 | hello9 | 3 | 1
I've fond complex queries and examples, but they didn't really helped.
You can do it using variables:
SELECT
id,
title,
group_id,
votes
FROM (
SELECT
id,
title,
group_id,
votes,
#rn := CASE WHEN #prev = group_id THEN #rn + 1 ELSE 1 END AS rn,
#prev := group_id
FROM table1, (SELECT #prev := -1, #rn := 0) AS vars
ORDER BY group_id DESC, votes DESC
) T1
WHERE rn <= 3
ORDER BY group_id, votes DESC
This is basically just the same as the following query in databases that support ROW_NUMBER:
SELECT
id,
title,
group_id,
votes
FROM (
SELECT
id,
title,
group_id,
votes,
ROW_NUMBER() OVER (PARTITION BY group_id ORDER BY votes DESC) AS rn
FROM student
) T1
WHERE rn <= 3
ORDER BY group_id, votes DESC
But since MySQL doesn't support ROW_NUMBER yet you have to simulate it, and that's what the variables are for. The two queries are otherwise identical. Try to understand the second query first, and hopefully the first should make more sense.