Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to specify condition in Count()?

Is it possible to specify a condition in Count()? I would like to count only the rows that have, for example, "Manager" in the Position column.

I want to do it in the count statement, not using WHERE; I'm asking about it because I need to count both Managers and Other in the same SELECT (something like Count(Position = Manager), Count(Position = Other)) so WHERE is no use for me in this example.

like image 343
agnieszka Avatar asked Sep 09 '09 14:09

agnieszka


People also ask

Is it possible to specify condition in count?

COUNT() with HAVINGThe HAVING clause with SQL COUNT() function can be used to set a condition with the select statement.

Can you put a select statement in a count?

SQL SELECT statement can be used along with COUNT(*) function to count and display the data values.

How do you use count in if condition in SQL?

SELECT [DISTINCT] COUNT([DISTINCT] IF(<condition>, <expression>, NULL)) AS alias_name FROM your_table_name; The syntax shows that: COUNT() function includes IF() function, which has a condition specified. If the <condition> is true, then the count will be calculated based on <expression> passed.

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

If you can't just limit the query itself with a where clause, you can use the fact that the count aggregate only counts the non-null values:

select count(case Position when 'Manager' then 1 else null end)
from ...

You can also use the sum aggregate in a similar way:

select sum(case Position when 'Manager' then 1 else 0 end)
from ...
like image 56
Guffa Avatar answered Oct 24 '22 02:10

Guffa


Assuming you do not want to restrict the rows that are returned because you are aggregating other values as well, you can do it like this:

select count(case when Position = 'Manager' then 1 else null end) as ManagerCount
from ...

Let's say within the same column you had values of Manager, Supervisor, and Team Lead, you could get the counts of each like this:

select count(case when Position = 'Manager' then 1 else null end) as ManagerCount,
    count(case when Position = 'Supervisor' then 1 else null end) as SupervisorCount,
    count(case when Position = 'Team Lead' then 1 else null end) as TeamLeadCount,
from ...
like image 243
D'Arcy Rittich Avatar answered Oct 24 '22 02:10

D'Arcy Rittich