4

假设我们有一个Emp包含EmpId, Manager, Subb三列的表。

Manager为 1 时EmpId为经理,同样为subb.

需要表中的经理和 subb 的数量。

我们可以将这两个查询组合成一个SELECT查询吗?(只想扫描一次表)

select count(*) as ManagerNumber from Emp where Manager=1
select count(*) as Subordinate  from Emp where Subb=1.
4

2 回答 2

10

你可以这样做:

SELECT 
  SUM(CASE WHEN Manager = 1 THEN 1 ELSE 0 END) AS ManagerNumber, 
  SUM(CASE WHEN subb = 1 THEN 1 ELSE 0 END) AS Subordinate 
FROM Emp 

它是 SQL ANSI 标准,适用于所有 RDBMS。

于 2012-09-26T11:29:27.893 回答
0

是的你可以。

select
    (select count(*) as ManagerNumber from Emp where Manager=1),
    (select count(*) as Subordinate  from Emp where Subb=1)

或者每一个连续,

select count(*) as ManagerNumber from Emp where Manager=1
UNION
    select count(*) as Subordinate  from Emp where Subb=1
于 2012-09-26T11:30:45.520 回答