是否可以在Count()中指定一个条件?我希望只计算在Position列中有“Manager”的行。

我想在count语句中做,而不是用WHERE;我正在询问它,因为我需要在相同的SELECT(类似count (Position = Manager), count (Position = Other))中计算经理和其他,所以在这个例子中,WHERE对我来说没有用处。


当前回答

假设你不想限制返回的行,因为你也在聚合其他值,你可以这样做:

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

假设在同一列中,你有经理,主管和团队领导的值,你可以得到每一个的计数如下所示:

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 ...

其他回答

SELECT COUNT(*) FROM bla WHERE Position = 'Manager'

我认为您可以使用一个简单的WHERE子句来只选择count some记录。

@Guffa的回答很好,只要指出可能用IF语句更干净就行了

select count(IIF(Position = 'Manager', 1, NULL)) as ManagerCount
from ...

如果使用Postgres或SQLite,可以使用Filter子句来提高可读性:

SELECT
  COUNT(1) FILTER (WHERE POSITION = 'Manager') AS ManagerCount,
  COUNT(1) FILTER (WHERE POSITION = 'Other') AS OtherCount
FROM ...

BigQuery也有Countif -在这里可以看到不同SQL方言对这些特性的支持: https://modern-sql.com/feature/filter

假设你不想限制返回的行,因为你也在聚合其他值,你可以这样做:

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

假设在同一列中,你有经理,主管和团队领导的值,你可以得到每一个的计数如下所示:

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 ...