Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multi-count of specific values

Tags:

mysql

count

sum

I have a table like this:

id|category

where category is an integer between 0 and 3. How do I count how many rows are in each category. Is it possible in a single query?

F.x. if I have these rows:

a|3
b|1
d|1
f|0
g|2

the result shoud be:

(1,2,1,1)

ie. 1 in category = 0, 2 in category = 1 etc.

like image 791
Muleskinner Avatar asked Apr 05 '11 14:04

Muleskinner


People also ask

How do I count multiple values in SQL?

You can count multiple COUNT() for multiple conditions in a single query using GROUP BY. SELECT yourColumnName,COUNT(*) from yourTableName group by yourColumnName; To understand the above syntax, let us first create a table.

How do I count multiple values in a column?

Use the COUNTIF function to count how many times a particular value appears in a range of cells.

How do I count different values in the same column in SQL?

To count the number of different values that are stored in a given column, you simply need to designate the column you pass in to the COUNT function as DISTINCT . When given a column, COUNT returns the number of values in that column. Combining this with DISTINCT returns only the number of unique (and non-NULL) values.


1 Answers

This will get you a row for each category.

SELECT category, COUNT(*) as catcount
    FROM YourTable
    GROUP BY category

To get output in the exact format you specified (1 row, 4 columns):

SELECT SUM(CASE WHEN category = 0 THEN 1 ELSE 0 END) AS cat0count,
       SUM(CASE WHEN category = 1 THEN 1 ELSE 0 END) AS cat1count,
       SUM(CASE WHEN category = 2 THEN 1 ELSE 0 END) AS cat2count,
       SUM(CASE WHEN category = 3 THEN 1 ELSE 0 END) AS cat3count
    FROM YourTable
like image 126
Joe Stefanelli Avatar answered Sep 29 '22 14:09

Joe Stefanelli