Jack
Jack

Reputation: 10037

SQL: Combine Select count(*) from multiple tables

How do you combine multiple select count(*) from different table into one return?

I have a similar sitiuation as this post

but I want one return.

I tried Union all but it spit back 3 separate rows of count. How do you combine them into one?

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'

edit: I'm on MS SQL 2005

Upvotes: 59

Views: 152806

Answers (8)

toquart
toquart

Reputation: 434

For 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;

Upvotes: 0

Bill Karwin
Bill Karwin

Reputation: 562260

I'm surprised no one has suggested this variation:

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'
);

Upvotes: 22

Chris J
Chris J

Reputation: 2206

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

This is an easy way.

Upvotes: 120

Gren
Gren

Reputation: 573

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

Upvotes: 1

Jason
Jason

Reputation: 1015

You can combine your counts like you were doing before, but then you could sum them all up a number of ways, one of which is shown below:

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

Upvotes: 3

Kris
Kris

Reputation: 41827

you could name all fields and add an outer select on those fields:

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

That should do the trick.

Upvotes: 0

Remus Rusanu
Remus Rusanu

Reputation: 294227

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

Upvotes: 18

Mitchel Sellers
Mitchel Sellers

Reputation: 63126

Basically you do the counts as sub-queries within a standard select.

An example would be the following, this returns 1 row, two columns

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

Upvotes: 10

Related Questions