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)
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.
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.
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.
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.
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With