Is it possible to specify condition in Count()?

2019-01-04 15:50发布

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.

11条回答
Juvenile、少年°
2楼-- · 2019-01-04 16:23

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 ...
查看更多
成全新的幸福
3楼-- · 2019-01-04 16:24

Note with PrestoDB SQL (from Facebook), there is a shortcut:

https://prestodb.io/docs/current/functions/aggregate.html

count_if(x) → bigint

Returns the number of TRUE input values. This function is equivalent to count(CASE WHEN x THEN 1 END)

查看更多
混吃等死
4楼-- · 2019-01-04 16:30

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 ...
查看更多
萌系小妹纸
5楼-- · 2019-01-04 16:30

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 using COUNT(): e.g.

SELECT SUM(CASE WHEN Position = 'Manager' THEN 1 ELSE 0 END) AS ManagerCount,
    SUM(CASE WHEN Position = 'CEO' THEN 1 ELSE 0 END) AS CEOCount
FROM SomeTable
查看更多
戒情不戒烟
6楼-- · 2019-01-04 16:30

Using this you'll get the count for managers

Select Position, count(*) as 'Position Counter'
from your_table 
group by Position 
查看更多
登录 后发表回答