Jac*_*ack 43 sql t-sql sql-server
如何将来自不同表的多个选择计数(*)组合成一个回报?
我和这篇文章有类似的情结
但我想要一次回归.
我尝试了所有的联盟,但它吐了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'
Run Code Online (Sandbox Code Playgroud)
编辑:我在MS SQL 2005上
Chr*_*s J 88
SELECT
(select count(*) from foo1 where ID = '00123244552000258')
+
(select count(*) from foo2 where ID = '00123244552000258')
+
(select count(*) from foo3 where ID = '00123244552000258')
Run Code Online (Sandbox Code Playgroud)
这是一种简单的方法.
Rem*_*anu 16
select
(select count(*) from foo) as foo
, (select count(*) from bar) as bar
, ...
Run Code Online (Sandbox Code Playgroud)
Bil*_*win 15
我很惊讶没有人建议这种变化:
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'
);
Run Code Online (Sandbox Code Playgroud)
基本上,您将计数作为标准选择中的子查询.
一个例子如下,这将返回1行,两列
SELECT
(SELECT COUNT(*) FROM MyTable WHERE MyCol = 'MyValue') AS MyTableCount,
(SELECT COUNT(*) FROM YourTable WHERE MyCol = 'MyValue') AS YourTableCount,
Run Code Online (Sandbox Code Playgroud)