MySQL SQL:如何获取列中每个不同值的计数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7053902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 20:51:01  来源:igfitidea点击:

SQL: How to get the count of each distinct value in a column?

mysqlsqlcount

提问by Jeff Gortmaker

I have a SQL table called "posts" that looks like this:

我有一个名为“posts”的 SQL 表,如下所示:

id | category
-----------------------
1  | 3
2  | 1
3  | 4
4  | 2
5  | 1
6  | 1
7  | 2

Each category number corresponds to a category. How would I go about counting the number of times each category appears on a post all in one sql query?

每个类别编号对应一个类别。我将如何计算每个类别在一个 sql 查询中全部出现在帖子中的次数?

As an example, such a query might return a symbolic array such as this: (1:3, 2:2, 3:1, 4:1)

例如,这样的查询可能会返回一个符号数组,如下所示: (1:3, 2:2, 3:1, 4:1)



My current method is to use queries for each possible category, such as: SELECT COUNT(*) AS num FROM posts WHERE category=#, and then combine the return values into a final array. However, I'm looking for a solution that uses only one query.

我目前的方法是对每个可能的类别使用查询,例如: SELECT COUNT(*) AS num FROM posts WHERE category=#,然后将返回值组合成一个最终的数组。但是,我正在寻找一种仅使用一个查询的解决方案。

回答by Dan Grossman

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category