我正在尝试做类似第一个回答的问题question添加输出排名的@part
,不知何故,我无法做到正确。
我正在使用的sql是:
select child.id, child.perCent
from likesd parent
join likesd child
on parent.id = child.parent
where parent.type = 3
order by parent.id, child.perCent desc;
我有些不能适应上述sql中的@
部分,并需要帮助。
SELECT first_name, // This sql is from the previous question
age,
gender,
@curRank := @curRank + 1 AS rank
FROM person p, (SELECT @curRank := 0) r
ORDER BY age;
所以:
select child.id, child.perCent, @curRank := @curRank + AS rank
from likesd parent, (SELECT @curRank := 0) r
join likesd child
on parent.id = child.parent
where parent.type = 3
order by parent.id, child.perCent desc;
最后,我想要实现的是所需的结果。你能看出我能做到这一点吗?
主要表
"id" "type" "parent" "country" "votes" "perCent"
"24" "1" "1" "US" "30" "0"
"25" "3" "24" "US" "30" "0"
"26" "10" "25" "US" "15" "50.00"
"27" "10" "25" "US" "10" "33.33"
"28" "10" "25" "US" "5" "16.66"
"29" "1" "1" "US" "50" "0"
"30" "3" "29" "US" "50" "0"
"31" "10" "30" "US" "20" "40.00"
"32" "10" "30" "US" "15" "25.00"
"33" "10" "30" "US" "15" "35.00"
预期结果:
"id" "perCent" "rank" // Rank is calculated based on the sql order above
"26" "50.00" "1"
"27" "33.33" "2"
"28" "16.66" "3"
"31" "40.00" "1" // New parent, new ranking
"33" "35.00" "2"
"32" "25.00" "3"
答案 0 :(得分:1)
试试这个:
select child.id,
child.perCent,
CASE parent.id
WHEN @curParent THEN @curRank := @curRank + 1
ELSE @curRank := 1 AND @curParent := parent.id END as Rank
from likesd parent, likesd child, (SELECT @curParent := 0, @curRank := 0) r
where parent.id = child.parent
and parent.type = 3
order by parent.id, child.perCent desc;
答案 1 :(得分:1)
select id, perCent,
@curRank := if(parent = @prevParent, @curRank + 1, 1) AS rank,
@prevParent := parent
from (
select child.id, child.perCent, child.parent
from likesd parent
join likesd child
on parent.id = child.parent
where parent.type = 3
order by parent.id, child.perCent desc) x
cross join (SELECT @curRank := 0, @prevParent := null) r