I\'m having problems running a query ranking. The inner SELECT gives the rows in order of ranking, for each line, the variable @rank increases, if not a position equal to th
First, Thank you all!
I found a way to return the expected result making other selects 2
A) Select first grouped and ordered
SELECT
SUM( a.value ) AS SUM_VALUES,
b.id AS b_id,
b.name AS b_name
FROM
a INNER JOIN b ON ( a.b_id = b.id )
GROUP BY b.id
ORDER BY SUM_VALUES DESC
B) I do this ranking list
SELECT
R.*,
@prev := @curr,
@curr := R.SUM_VALUES,
@rank := IF(@prev = @curr, @rank, @rank+1) AS rank
FROM (
SELECT
SUM( a.value ) AS SUM_VALUES,
b.id AS b_id,
b.name AS b_name
FROM
a INNER JOIN b ON ( a.b_id = b.id )
GROUP BY b.id
ORDER BY SUM_VALUES DESC
) AS R
C) And lastly, just select what matters
SELECT
Ranking.b_id,
Ranking.b_name,
Ranking.rank
FROM
(
SELECT
R.*,
@prev := @curr,
@curr := R.SUM_VALUES,
@rank := IF(@prev = @curr, @rank, @rank+1) AS rank
FROM (
SELECT
SUM( a.value ) AS SUM_VALUES,
b.id AS b_id,
b.name AS b_name
FROM
a INNER JOIN b ON ( a.b_id = b.id )
GROUP BY b.id
ORDER BY SUM_VALUES DESC
) AS R
) AS Ranking
WHERE
Ranking.b_id = 1
The result of this query was:
+------+--------+------+
| b_id | b_name | rank |
+------+--------+------+
| 1 | AAA | 2 |
+------+--------+------+