Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Query to get total rows and total rows matching specific condition

Tags:

mysql

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

like image 245
mrN Avatar asked Jan 12 '11 06:01

mrN


People also ask

How do I COUNT matching rows in SQL?

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.

Can we use SUM and COUNT together in SQL?

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.

How do I COUNT specific items in SQL?

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.

Can we use COUNT function in WHERE clause?

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.


2 Answers

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

like image 142
a1ex07 Avatar answered Nov 15 '22 08:11

a1ex07


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
like image 35
Adriaan Stander Avatar answered Nov 15 '22 07:11

Adriaan Stander