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.
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.
Use the COUNTIF function to count how many times a particular value appears in a range of cells.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With