Reputation: 10037
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
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
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
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
Reputation: 573
select sum(counts) from (
select count(1) as counts from foo
union all
select count(1) as counts from bar)
Upvotes: 1
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
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
Reputation: 294227
select
(select count(*) from foo) as foo
, (select count(*) from bar) as bar
, ...
Upvotes: 18
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