SQL:组合从多个表中选择计数(*)

时间:2009-08-14 18:56:57

标签: sql sql-server tsql

如何将来自不同表的多个选择计数(*)组合成一个回报?

我有与此post

类似的情境

但我想要一次回归。

我尝试了所有的联盟,但它吐了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

8 个答案:

答案 0 :(得分:85)

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

这是一种简单的方法。

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

答案 2 :(得分:14)

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

答案 3 :(得分:7)

基本上,您将计数作为标准选择中的子查询。

以下是一个例子,它返回1行,两列

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

答案 4 :(得分:2)

你可以像以前那样合并你的计数,但是你可以通过多种方式对它们进行总结,其中一种如下所示:

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

答案 5 :(得分:0)

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

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

这应该可以解决问题。

答案 6 :(得分:0)

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

答案 7 :(得分:0)

对于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;