是否可以在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对我来说没有用处。
当前回答
你的意思是:
SELECT Count(*) FROM YourTable WHERE Position = 'Manager'
如果是这样,那么是的,这是可行的!
其他回答
假设你不想限制返回的行,因为你也在聚合其他值,你可以这样做:
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 ...
注意使用PrestoDB SQL(来自Facebook),有一个快捷方式:
https://prestodb.io/docs/current/functions/aggregate.html
Count_if (x)→bigint 返回TRUE输入值的个数。这 函数等价于count(CASE WHEN x THEN 1 END)
以下是我所做的,以获得一个数据集,其中包括每个集装箱内满足标准的总数和数量。让我来回答这个问题"有多少集装箱的货物超过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
你的意思是:
SELECT Count(*) FROM YourTable WHERE Position = 'Manager'
如果是这样,那么是的,这是可行的!
如果你不能用where子句限制查询本身,你可以使用count聚合只计算非空值的事实:
select count(case Position when 'Manager' then 1 else null end)
from ...
你也可以用类似的方式使用sum聚合:
select sum(case Position when 'Manager' then 1 else 0 end)
from ...