2013-11-15 47 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