假设我们有一个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.
答案 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