簡體   English   中英

MYSQL:分組和計數問題

[英]MYSQL: group by and count issues

我已經對此問題進行了研究,但是找不到解決方案。

在此處輸入圖片說明

我如何獲得這樣的輸出?

在此處輸入圖片說明

您可以將原始表連接到一個子查詢,該子查詢對每所學校的學生進行計數。

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_concat

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

學生將由separeted ,在一行中的每個學校。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM