开发者

How to get the count of each distinct value in a column? [duplicate]

开发者 https://www.devze.com 2023-03-28 03:43 出处:网络
This question already has answers here: Count the occurrences of DISTINCT values 开发者_C百科 (4 answers)
This question already has answers here: Count the occurrences of DISTINCT values 开发者_C百科 (4 answers) Closed 1 year ago.

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

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?

As an example, such a query might return a symbolic array such as this: (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
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category
0

精彩评论

暂无评论...
验证码 换一张
取 消