【问题标题】:Calculating ranks from the following data [duplicate]从以下数据计算排名[重复]
【发布时间】:2013-11-29 02:42:12
【问题描述】:

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

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

parent 保存total 列中所有行的total,以及votes 中的total 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"

【问题讨论】:

  • 你应该可以使用this question中的答案,除非你使用IF(type = 10, @curRank := @curRank + 1 AS rank, 0) as Rank
  • @barmar 我很接近。如果你读到这篇文章,你能帮忙解决这个问题吗:stackoverflow.com/questions/20015937/… 我有点难以在其中添加@ 部分。

标签: mysql sql


【解决方案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 ) ) )

【讨论】:

  • 效果很好。我希望我能够像我的问题中的更新声明那样做到这一点,所有孩子都一次性更新他们的父母,因为这实际上是一个更新。
猜你喜欢
  • 2012-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-04
  • 2021-09-13
  • 1970-01-01
  • 2013-08-03
  • 2015-04-15
相关资源
最近更新 更多