是否可以在Count()中指定一个条件?我希望只计算在Position列中有“Manager”的行。
我想在count语句中做,而不是用WHERE;我正在询问它,因为我需要在相同的SELECT(类似count (Position = Manager), count (Position = Other))中计算经理和其他,所以在这个例子中,WHERE对我来说没有用处。
是否可以在Count()中指定一个条件?我希望只计算在Position列中有“Manager”的行。
我想在count语句中做,而不是用WHERE;我正在询问它,因为我需要在相同的SELECT(类似count (Position = Manager), count (Position = Other))中计算经理和其他,所以在这个例子中,WHERE对我来说没有用处。
当前回答
如果使用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(*) FROM YourTable WHERE Position = 'Manager'
如果是这样,那么是的,这是可行的!
@Guffa的回答很好,只要指出可能用IF语句更干净就行了
select count(IIF(Position = 'Manager', 1, NULL)) as ManagerCount
from ...
我认为您可以使用一个简单的WHERE子句来只选择count some记录。
假设你不想限制返回的行,因为你也在聚合其他值,你可以这样做:
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 ...
以下是我所做的,以获得一个数据集,其中包括每个集装箱内满足标准的总数和数量。让我来回答这个问题"有多少集装箱的货物超过X%大于51号"
select
Schedule,
PackageNum,
COUNT (UniqueID) as Total,
SUM (
case
when
Size > 51
then
1
else
0
end
) as NumOverSize
from
Inventory
where
customer like '%PEPSI%'
group by
Schedule, PackageNum