MYSQL:分组和计数问题

时间:2017-01-05 05:38:56

标签: mysql

我已经对这个问题进行过研究,但我找不到解决方案。

enter image description here

如何获得这样的输出?

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以将原始表格加入子查询,该子查询统计每所学校的学生。

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

答案 1 :(得分:0)

如果你真的希望每个学生都出现在行中,你应该这样做:

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_concat

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

每个学校的学生将由,分成一排。