OK, Here is what my table looks like
------------------------------------------------
id type
-----------------------------------------------
1 a
2 b
3 a
4 c
5 c
7 a
8 a
------------------------------------------------
Now, I need a query that can give me this output...
-----------------------------------------------------------------
count(*) | count(type=a) | count(type=b) | count(type=c)
-----------------------------------------------------------------
8 4 1 3
------------------------------------------------------------------
I only know to get the total set using count(*), but how to do the remaining
The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.
SQL SUM() and COUNT() with inner joinThese two tables can be joined by themselves and to return a result. Here is a slide presentation of all aggregate functions.
In SQL, you can make a database query and use the COUNT function to get the number of rows for a particular group in the table. Here is the basic syntax: SELECT COUNT(column_name) FROM table_name; COUNT(column_name) will not include NULL values as part of the count.
SQL SELECT COUNT() can be clubbed with SQL WHERE clause. Using the WHERE clause, we have access to restrict the data to be fed to the COUNT() function and SELECT statement through a condition.
SELECT
COUNT(*),
COUNT(CASE WHEN type='a' THEN 1 END) as count_a,
COUNT(CASE WHEN type='b' THEN 1 END) as count_b,
COUNT(CASE WHEN type='c' THEN 1 END) as count_c,
FROM table1;
//or you can do
SELECT type, COUNT(*)
FROM table1
GROUP BY type WITH ROLLUP
In the latter case you will get results :
a | 4
b | 1
c | 3
null | 8
You could try something like
SELECT COUNT(*) Total,
SUM(CASE WHEN type='a' THEN 1 ELSE 0 END) as CountOfA,
SUM(CASE WHEN type='b' THEN 1 ELSE 0 END) as CountOfB,
SUM(CASE WHEN type='c' THEN 1 ELSE 0 END) as CountOfC,
FROM Table
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