我有一个类和类的类别列表。我想显示每个类别有多少个类。像这样的东西:
category | # of classes
Sports | 12
Fitness | 32
Climbing | 8
Run Code Online (Sandbox Code Playgroud)
该表的设置使每个类都位于包含类别的行上。
category | class_name
fitness | Learn to Skate
Run Code Online (Sandbox Code Playgroud)
我有以下 SQL,它生成不同类别的列表:
select
distinct category
from classes
order by category asc
; Output:
; Fitness
; Climbing
; Recreation
; ...
Run Code Online (Sandbox Code Playgroud)
我还想显示有多少个类。我认为这很简单:
select
distinct category,
count(distinct category)
from classes
order by category asc
; Output:
; Fitness | 11
Run Code Online (Sandbox Code Playgroud)
输出几乎有效,但它只产生一行。没有count()
它,它会产生 11 行,正如预期的那样。为什么这只产生一行?我怎样才能做到这一点?
您正在使用COUNT
没有GROUP BY
子句的聚合函数 ( ) ,然后 mysql 不知道您想要如何聚合数据:
SELECT
category,
count(category) as category_count
FROM classes
GROUP BY category
ORDER BY category ASC
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3368 次 |
最近记录: |