选择记录并按分数desc排序

时间:2013-11-16 05:23:54

标签: mysql sql

从以下数据中,如何通过这些孩子的perCent desc选择父母订购的所有孩子?

父母只是3型。

我尝试了以下内容,但是命令整个结果集。我需要由每位父母的孩子按照订单进行订购。你会看到预期的结果:

select b.id, b.type, b.perCent from scores a 
INNER JOIN scores b on a.id = b.parent and a.type=3 order by b.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"    "29"        "US"        "20"    "40.00"
"32"    "10"    "29"        "US"        "15"    "25.00"
"33"    "10"    "29"        "US"        "15"    "35.00"

预期结果:

"id"    "perCent" //Ordered by each parents childrens perCent desc
"26"    "50.00"
"27"    "33.33"
"28"    "16.66"

"31"    "40.00"
"33"    "35.00"
"32"    "25.00"

3 个答案:

答案 0 :(得分:1)

select id,perCent from scores 
where parent in (select id from scores where type=3)
order by parent, percent desc

答案 1 :(得分:1)

保持相同的常规联接,但跨多个列应用订单:

select child.id as childId, child.perCent
from scores parent
join scores child
   on parent.id = child.parent
where parent.type = 3
order by parent.id, child.perCent desc

这就是说,父母的第一个命令(这样父母的所有孩子将一起出现)然后由每个孩子(按照所述父母)的顺序递减百分比。

请注意,即使未选择parent.id列,它仍有资格进行订购。

答案 2 :(得分:0)

试试这个

select GROUP_CONCAT(id),GROUP_CONCAT(type),GROUP_CONCAT(parent) from atab where type = 10 group by parent  order by id 

在这里,您将获得以id排序的逗号分隔值 SQLFiddle