sql查询计数最大子级数

hxzsmxv2  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(311)

我期待着显示有关家长与最多的孩子的信息。下面的查询可以工作,但是,我在从族表添加更多列名时遇到了问题,例如 first_name , last_name . 我错过了什么?
sql语句—显示子级数最多的父级

SELECT w.Parent, count(*) AS 'Number of children'
FROM family w,
     family m
WHERE w.Parent = m.pid
GROUP BY w.Parent
HAVING count(*) =
    (SELECT MAX (mycount)
    FROM
        (SELECT count(*) mycount
        FROM family
        GROUP BY Parent) a);

当前输出父项=101子项数=4

xtfmy6hx

xtfmy6hx1#

学会正确使用 JOIN 语法!
从查询开始,以获取具有最多子级的父级:

select top (1) with ties parent, count(*) as cnt
from family f
group by parent
order by cnt desc

然后加入到 family 获取更多信息:

select f.*
from family f join
     (select top (1) with ties parent, count(*) as cnt
      from family f
      group by parent
      order by cnt desc
     ) pc
     on pc.parent = f.pid
mzmfm0qo

mzmfm0qo2#

显示 first_name 或者 last_name 对于父级,可以执行以下操作:

SELECT w.Parent, MIN(w.first_name) AS first_name, MIN(w.last_name) AS last_name, count(*) AS 'Number of children' 
FROM family w, family m 
WHERE w.Parent = m.pid 
GROUP BY w.Parent 
HAVING count() = (
    SELECT MAX (mycount) 
    FROM (
        SELECT count(*) mycount FROM family GROUP BY Parent
    ) 
a);
jvlzgdj9

jvlzgdj93#

只需加入(正确)和分组:

select top (1) P.First_Name, P.Last_Name
    , count(*) [Number of children]
from dbo.Family P
inner join dbo.Family C on C.Parent = P.id
group by P.First_Name, P.Last_Name
order by [Number of children] desc;

然后对于从中显示的每个附加列 P ,按同一列分组。

相关问题