MYSQL:分组和计数问题

MYSQL:分组和计数问题,mysql,Mysql,我已经对这个问题做了研究,但找不到解决办法 如何获得这样的输出 您可以将原始表连接到一个子查询,该子查询统计每所学校的学生人数 SELECT t1.student, t2.count, t1.school FROM yourTable t1 INNER JOIN ( SELECT school, COUNT(*) AS count FROM yourTable GROUP BY school ) t2 ON t1.school = t

我已经对这个问题做了研究,但找不到解决办法

如何获得这样的输出


您可以将原始表连接到一个子查询,该子查询统计每所学校的学生人数

SELECT t1.student,
       t2.count,
       t1.school
FROM yourTable t1
INNER JOIN
(
    SELECT school, COUNT(*) AS count
    FROM yourTable
    GROUP BY school
) t2
    ON t1.school = t2.school
ORDER BY t2.count DESC,
         t1.school
请注意,您的预定顺序在问题中并不清楚。您可能一直在寻找此订单:

ORDER BY t1.school,
         t1.count    -- or t2.count DESC

如果您真的希望每个学生以行的形式出现,您应该这样做:

select
    yourtable.student, t.cnt as `count`, t.school
from (
    select count(id) as cnt, school
    from yourtable
    group by school
) t
left join yourtable
on yourtable.school = t.school
order by t.school, yourtable.id
或者,如果您只需要每个学校的所有学生,您可以使用
group\u concat

select
    group_concat(student) as student,
    count(id) as `count`,
    school
from yourtable
group by school

每个学校的学生将被
分隔成一行。

请发布您的累了的内容?请查看如何寻求家庭作业帮助。此外,该条款还规定,“要求家庭作业帮助的问题必须包括你迄今为止为解决问题所做的工作的摘要以及你解决问题的困难的描述。”我已经为你做了TOTORNX研究,先生,我将尝试:)但这将包括
d
学生行,而不是将
h
student行加倍。。。OP结果显示学生
a
e
h
h
,而不是
a
d
e
h
h
,斯宾塞7593我猜这是个打字错误,否则就没什么意义了。啊,对不起,先生,输入错误:)但是非常感谢您的回复。您不需要在这里使用
左连接
,因为原始表中的每个学校都保证出现在子查询中。@TimBiegeleisen Right,可能不需要,但是
左连接也有效:-)@ZEdmarSanchez Group by就如Forward建议的那样足够了。好一个前锋!
SELECT t1.student,
       t2.count,
       t1.school
FROM yourTable t1
INNER JOIN
(
    SELECT school, COUNT(*) AS count
    FROM yourTable
    GROUP BY school
) t2
    ON t1.school = t2.school
ORDER BY t2.count DESC,
         t1.school