0

我试图从下面的数据中找出父母有多少孩子。这levellevel和父级是idrow链接到的。我正在尝试输出数据,按级别和孩子的数量排列。

我拼凑了下面的 sql,但这并没有真正按照我想要的方式返回结果:

select id, level, count(parent) as p, country 
  from stats group by level order by level asc, p desc;

你能帮我吗?

表数据

"id"    "level" "parent"    "country"
"1"     "1"     "0"         "US"
"2"     "2"     "1"         "US"
"3"     "2"     "1"         "US"
"4"     "2"     "1"         "US"
"5"     "2"     "1"         "US"

"6"     "3"     "2"         "US"
"7"     "3"     "2"         "US"

"8"     "1"     "0"         "US"

"9"     "2"     "8"         "US"
"10"    "2"     "8"         "US"
"11"    "2"     "8"         "US"

"12"    "3"     "9"         "US"
"13"    "3"     "9"         "US"
"14"    "3"     "9"         "US"

"15"    "3"     "10"        "US"
"16"    "3"     "10"        "US"
"17"    "3"     "10"        "US"
"18"    "3"     "10"        "US"

期望的输出

"id"    "type"  "country"   "Count"
"1"     "1"     "US"        "4"
"8"     "1"     "US"        "3"
"10"    "2"     "US"        "4"
"9"     "2"     "US"        "3"
"2"     "2"     "US"        "2"
4

3 回答 3

2

尝试这个:

SELECT s.id, s.level, s.country, x.cnt 
FROM stats s, 
(SELECT DISTINCT(parent), COUNT(*) AS cnt 
FROM stats GROUP BY parent) x 
WHERE s.id = x.parent ORDER BY s.parent;

这样,它的顺序是首先显示层次结构中的较高者。

于 2013-09-27T14:33:02.520 回答
0

获取按父母分组的计数并将其加入列表以获取其他详细信息:

select idt.id as id, idt.level as type, idt.country as country, idc.ct as Count
from stats idt
inner join
(
  select parent, count(id) as ct
  from stats
  group by parent
) idc
on idt.id=idc.parent
order by level asc
于 2013-09-27T14:32:52.610 回答
0

它可能是这样的 - 在 SELECT 部分添加您想要的列:

SELECT
  s.id,
  IF (p.number IS NULL,0,p.number) AS number
  FROM stats s
    LEFT JOIN
    (
      SELECT
        parent,
        COUNT(*) AS number
        FROM stats
        GROUP BY parent
        WHERE parent!=0
    ) p
    ON s.id=p.parent
  ORDER BY s.level ASC, p.number DESC
于 2013-09-27T14:33:23.453 回答