2013-11-15 22 views
1

如何使用just sql计算以下数据中所有"type 10"行的排名?从以下数据计算排名

sql将进入存储过程,不涉及其他脚本。

parent持有total列中的所有行的total,并在votestotal 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

您应该能够使用的答案[这个问题](http://stackoverflow.com/questions/3333665/mysql-rank-function/3333697#3333697),只是使用'IF(类型= 10,@curRank:= @curRank + 1 AS排名,0)作为Rank' – Barmar

+0

@barmar我很接近。如果你读了这可以帮助你解决这个问题:http://stackoverflow.com/questions/20015937/incorporating-a-ranking-system-into-this-sql我有点坚持添加'@'部分那里。 – jmenezes

回答

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 

SQL Fiddle

SQL Fiddle

UPDATE scores SET rank= (FIND_IN_SET(votes, (
SELECT * FROM(SELECT GROUP_CONCAT(votes 
ORDER BY votes DESC) 
FROM scores WHERE type=10)x))) 
+0

非常好地工作。我希望我能够像在我的问题的更新声明中那样做,所有的孩子都一次更新他们的父母,因为这实际上是一个更新。 – jmenezes