如果我有这样的表和数据:
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)";
但它只会为我返回一个结果。
有任何提示吗?谢谢。
答案 0 :(得分:112)
您需要首先聚合数据,这可以使用GROUP BY子句完成:
SELECT Group, COUNT(*)
FROM table
GROUP BY Group
ORDER BY COUNT(*) DESC
DESC关键字允许您首先显示最高计数,按默认顺序显示ORDER BY按升序显示最低计数。
答案 1 :(得分: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
顺序返回订单
答案 2 :(得分:2)
SELECT * FROM table
group by `Group`
ORDER BY COUNT(Group)
答案 3 :(得分:2)
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
答案 4 :(得分:0)
下面给出了我对你所拥有的内容。 (通知组列)
SELECT
*
FROM
myTable
GROUP BY
Group_value,
ID
ORDER BY
count(Group_value)
请告诉我这件事是否合适......
我想要得到你想要的东西......
答案 5 :(得分:0)
尝试使用以下查询:
SELECT
GROUP,
COUNT(*) AS Total_Count
FROM
TABLE
GROUP BY
GROUP
ORDER BY
Total_Count DESC
答案 6 :(得分:0)
Q值。列出每个节目的名称,以及它所持有的不同次数。 列出最常见的节目。
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
答案 7 :(得分:0)
...其他答案似乎都没有问问者的要求。
对于列为“组”的名为“事物”的表:
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