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.
If you can't just limit the query itself with a
where
clause, you can use the fact that thecount
aggregate only counts the non-null values:You can also use the
sum
aggregate in a similar way:Note with PrestoDB SQL (from Facebook), there is a shortcut:
https://prestodb.io/docs/current/functions/aggregate.html
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:
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:
Depends what you mean, but the other interpretation of the meaning is where you want to count rows with a certain value, but don't want to restrict the
SELECT
to JUST those rows...You'd do it using
SUM()
with a clause in, like this instead of usingCOUNT()
: e.g.Using this you'll get the count for managers