SQL按计数顺序


72

如果我有这样的表和数据:

ID |  Name  |  Group   

1    Apple     A    

2    Boy       A

3    Cat       B

4    Dog       C

5    Elep      C

6    Fish      C

我希望按照从小到大的Group总数进行排序,例如:A-2个记录,B-1个记录,C-3个记录,因此它将变为:

3    Cat       B

1    Apple     A    

2    Boy       A

4    Dog       C

5    Elep      C

6    Fish      C

我试过了

    $sql = "SELECT ID,Name FROM table ORDER BY COUNT(Group)";

但这只会为我返回一个结果。

有什么提示吗?谢谢。

Answers:


142

您需要首先聚合数据,这可以使用GROUP BY子句完成:

SELECT Group, COUNT(*)
FROM table
GROUP BY Group
ORDER BY COUNT(*) DESC

关键字DESC允许您首先显示最高计数,默认情况下按ORDER BY升序排列,这将首先显示最低计数。


非常感谢您的回答,但每组仅返回一个结果吗?例如:Cat,B | 苹果 Dog,C
Irene Ling

1
您正在运行此代码还是其他一些代码?根据第一个表,您提供的查询结果为:C 3 A 2 B 1
文斯·佩尔古里齐

你应该更喜欢(*)我想,而不是使用计数次数(1)
塞德里克VIDREQUIN

6

...其他答案似乎都没有像问问者所要求的那样。

对于列为“组”的名为“事物”的表:

SELECT
  things.*, counter.count
FROM
  things
LEFT JOIN (
  SELECT
    things.group, count(things.group) as count
  FROM
    things
  GROUP BY
    things.group
) counter ON counter.group = things.group
ORDER BY
  counter.count ASC;

这使:

id | name  | group | count 
---------------------------
3  | Cat   | B     | 1
1  | Apple | A     | 2
2  | Boy   | A     | 2
4  | Dog   | C     | 3
5  | Elep  | C     | 3
6  | Fish  | C     | 3

6
SELECT group, COUNT(*) FROM table GROUP BY group ORDER BY group

或按数量订购

SELECT group, COUNT(*) AS count FROM table GROUP BY group ORDER BY count DESC

3

尝试:

SELECT count(*),group FROM table GROUP BY group ORDER BY group

按降序排序

SELECT count(*),group FROM table GROUP BY group ORDER BY count(*) DESC

这将通过group返回group和的列对结果进行分组,count并按顺序返回group顺序


感谢您的协助,我尝试了一下,但是每组返回一个结果吗?例如:Cat,B | 苹果 狗,C。
Irene Ling

@IreneLing我没有在选择语句中包括名称-选中它
Manse 2012年


0

尝试使用以下查询:

SELECT
    GROUP,
    COUNT(*) AS Total_Count
FROM
    TABLE
GROUP BY
    GROUP
ORDER BY
    Total_Count DESC

0

下面给出了与您相反的信息。(通知组列)

SELECT
    *
FROM
    myTable
GROUP BY
    Group_value,
    ID
ORDER BY
    count(Group_value)

让我知道您是否还好...

我也想得到你想要的...


感谢您的回答,但很抱歉,它没有给我正确的结果。
Irene Ling

0

问:列出每个节目的名称,以及举行该节目的不同次数。列出最常举行的节目。

event_id show_id event_name judge_id
0101    01  Dressage        01
0102    01  Jumping         02
0103    01  Led in          01
0201    02  Led in          02
0301    03  Led in          01
0401    04  Dressage        04
0501    05  Dressage        01
0502    05  Flag and Pole   02

答:

select event_name, count(show_id) as held_times from event 
group by event_name 
order by count(show_id) desc
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.