Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum multiple SQL queries together?

Tags:

sql

sql-server

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?

like image 806
user198923 Avatar asked Nov 13 '09 15:11

user198923


People also ask

How do I SUM multiple values in one column in SQL?

The SUM() function sums up all the values in a given column or the values returned by an expression (which could be made up of numbers, column values, or both). It's a good introduction to SQL's aggregate functions, so let's dive right in!

How do I SUM all items in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.

Can you use SUM () in a GROUP BY SQL?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.


2 Answers

Not 100% sure what you mean, but maybe:

SELECT (SELECT COUNT(*) FROM tableA)+(SELECT COUNT(*) FROM tableB)
like image 139
Andrew G. Johnson Avatar answered Sep 18 '22 17:09

Andrew G. Johnson


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.

like image 45
davek Avatar answered Sep 19 '22 17:09

davek