user198923
user198923

Reputation: 489

How to sum multiple SQL queries together?

I'm trying to run multiple queries on multiple tables- similar to "select count(*) from TableA where x=1" per table.

What I'd like to do, is get all of the count(*) values that are returned and sum them into a single value...

Any ideas?

Upvotes: 11

Views: 26288

Answers (2)

davek
davek

Reputation: 22915

select sum(individual_counts) from
(
  select count(*) as individual_counts from TableA where x = 1
    union all
  select count(*) from TableB where x = 2
....
) as temp_table_name

you normally only need the alias on the first select when using a union.

Upvotes: 19

Andrew G. Johnson
Andrew G. Johnson

Reputation: 26993

Not 100% sure what you mean, but maybe:

SELECT (SELECT COUNT(*) FROM tableA)+(SELECT COUNT(*) FROM tableB)

Upvotes: 11

Related Questions