如何使用sql计算以下数据中所有"type 10"
行的排名?
sql将进入存储过程,不涉及其他脚本。
parent
包含total
列中所有行的total
和total votes
中的votes
。
我使用此更新perCent
col,所以这应该给你一个想法。也许随着这个计算排名?
所有行都按父级链接 - >孩子的关系。
全部基于总票数和候选人总数。候选人是10
UPDATE likesd p
JOIN likesd h
ON p.parent = h.id
AND p.country = h.country
SET p.percent = TRUNCATE(100*p.votes/h.votes,2);
原始数据
"id" "type" "parent" "country" "votes" "perCent" "total" "rank"
"24" "1" "1" "US" "30" "0" "" "0"
"25" "3" "24" "US" "30" "0" "3" "0"
"26" "10" "25" "US" "15" "50.00" "" "0"
"27" "10" "25" "US" "5" "16.66" "" "0"
"28" "10" "25" "US" "10" "33.33" "" "0"
期望的结果
"id" "type" "parent" "country" "votes" "perCent" "total" "rank"
"24" "1" "1" "US" "30" "0" "" "0"
"25" "3" "24" "US" "30" "0" "3" "0"
"26" "10" "25" "US" "15" "50.00" "" "1" // Rank 1. Has 15 votes out of 30 (see parent row above)
"27" "10" "25" "US" "5" "16.66" "" "3" // And so on.
"28" "10" "25" "US" "10" "33.33" "" "2"
答案 0 :(得分:1)
SELECT id,type,parent,country,votes,perCent,total, FIND_IN_SET( votes, (
SELECT GROUP_CONCAT( votes
ORDER BY votes DESC )
FROM table WHERE type=10 )
) AS rank
FROM table
UPDATE scores SET rank= (FIND_IN_SET(votes, (
SELECT * FROM(SELECT GROUP_CONCAT( votes
ORDER BY votes DESC )
FROM scores WHERE type=10)x ) ) )