是否可以在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'
如果是这样,那么是的,这是可行的!
其他回答
如果使用SQL 2005或更高版本,也可以使用Pivot关键字
更多信息来自Technet
SELECT *
FROM @Users
PIVOT (
COUNT(Position)
FOR Position
IN (Manager, CEO, Employee)
) as p
测试数据集
DECLARE @Users TABLE (Position VARCHAR(10))
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('CEO')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
我认为您可以使用一个简单的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 ...
@Guffa的回答很好,只要指出可能用IF语句更干净就行了
select count(IIF(Position = 'Manager', 1, NULL)) as ManagerCount
from ...
如果你不能用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 ...