将来自同一个表的两个SELECT语句组合在一起。条件

时间:2012-09-26 11:28:46

标签: sql

假设我们有一个Emp表,其中EmpId, Manager, Subb为三列。

Manager是经理时,

EmpId为1,类似于subb

要求表中的经理和子数量。

我们可以将这两个查询合并到一个SELECT查询中吗? (想要只扫描一次表)

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

2 个答案:

答案 0 :(得分: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。

答案 1 :(得分: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