SQL:结合从多个表中select计数(*)

如何将来自不同表格的多个select计数(*)合并为一个返回?

我有一个类似的这个职位 sitiuation

但我想要一个回报。

我试了联盟所有,但它吐了3个单独的计数行。 你怎么把它们合并成一个?

select count(*) from foo1 where ID = '00123244552000258' union all select count(*) from foo2 where ID = '00123244552000258' union all select count(*) from foo3 where ID = '00123244552000258' 

编辑:我在MS SQL 2005

 SELECT (select count(*) from foo1 where ID = '00123244552000258') + (select count(*) from foo2 where ID = '00123244552000258') + (select count(*) from foo3 where ID = '00123244552000258') 

这是一个简单的方法。

 select (select count(*) from foo) as foo , (select count(*) from bar) as bar , ... 

我很惊讶没有人提出这个变化:

 SELECT SUM(c) FROM ( SELECT COUNT(*) AS c FROM foo1 WHERE ID = '00123244552000258' UNION ALL SELECT COUNT(*) FROM foo2 WHERE ID = '00123244552000258' UNION ALL SELECT COUNT(*) FROM foo3 WHERE ID = '00123244552000258' ); 

基本上你在一个标准的select内作为子查询计数。

下面是一个例子,返回1行,2列

 SELECT (SELECT COUNT(*) FROM MyTable WHERE MyCol = 'MyValue') AS MyTableCount, (SELECT COUNT(*) FROM YourTable WHERE MyCol = 'MyValue') AS YourTableCount, 

你可以像你之前做的那样把你的计数结合起来,但是你可以用很多方法将它们总结起来,其中一个如下所示:

 SELECT SUM(A) FROM ( SELECT 1 AS A UNION ALL SELECT 1 AS A UNION ALL SELECT 1 AS A UNION ALL SELECT 1 AS A ) AS B 

您可以命名所有字段并在这些字段上添加外部select:

 SELECT A, B, C FROM ( your initial query here ) TableAlias 

这应该够了吧。

 select sum(counts) from ( select count(1) as counts from foo union all select count(1) as counts from bar) 

对于oracle:

 select( select count(*) from foo1 where ID = '00123244552000258' + select count(*) from foo2 where ID = '00123244552000258' + select count(*) from foo3 where ID = '00123244552000258' ) total from dual;