Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql sum of counts

I have two tables and want the total number of rows in each. The actual query is more complex as there will be where... clauses for each count

How do I do the following in t-sql (neither of which works)?

select count(*) from table1 + count(*) from table2

or

select sum(count(*) from table1,count(*) from table2)
like image 731
derekcohen Avatar asked May 26 '11 05:05

derekcohen


People also ask

Can you do a SUM of count 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.

How do I get the SUM and count in SQL query?

SQL SUM() and COUNT() using variable SUM of values of a field or column of a SQL table, generated using SQL SUM() function can be stored in a variable or temporary column referred as alias. The same approach can be used with SQL COUNT() function too.

How do I SUM aggregate in SQL?

The SQL Server SUM() function is an aggregate function that calculates the sum of all or distinct values in an expression. In this syntax: ALL instructs the SUM() function to return the sum of all values including duplicates. ALL is used by default.

Is SUM 1 the same as count (*)?

Lots of people find it surprising that COUNT(*) and COUNT(1) gave exactly the same performance. Many even asked if which one is better SUM(1) or COUNT(*). The answer is very simple and straightforward. Both are equal.

How do I count total data in SQL?

In SQL, you can make a database query and use the COUNT function to get the number of rows for a particular group in the table. Here is the basic syntax: SELECT COUNT(column_name) FROM table_name; COUNT(column_name) will not include NULL values as part of the count.

What is the difference between count () and SUM ()?

What is the difference between SUM and COUNT? Very simply, SUM calculates a total for a number of cells or values, so it's answering the question: HOW MUCH? Or, WHAT IS THE TOTAL? COUNT tells you HOW MANY cells meet a certain condition.


1 Answers

select SUM(cnt) from
(
    select COUNT(*) as cnt from table1 where /* where conditions */
    union all
    select COUNT(*) from table2 where /* where conditions */
) t

Would seem to do the trick, keep the queries of the different tables separate, and extend to more tables easily.

like image 99
Damien_The_Unbeliever Avatar answered Sep 25 '22 02:09

Damien_The_Unbeliever