Click here to Skip to main content
15,891,597 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a query
which counts the records from a table

select COunt(*) from table_1

and another query
which counts the records from other table

select COunt(*) from table_2

how can I get total records
i mean that sum of both the queries

record of table_1 and record of table_2
added in single field

using only a sql query
Posted

SQL
DECLARE @sum1 int
DECLARE @sum2 int

SET @Sum1 = SELECT COUNT(*) FROM Table1
SET @Sum2 = SELECT COUNT(*) FROM Table2

SELECT 
      @Sum1 As SumTable1, 
      @Sum2 as SumTable2, 
      @Sum1 + @Sum2 As Total


or just

SQL
SELECT (SELECT COUNT(*) FROM Table_1) As count1,
       (SELECT COUNT(*) FROM Table_2) As count2,
       (SELECT COUNT(*) FROM Table_1)+(SELECT COUNT(*) FROM Table_2) as total


only the total

SQL
SELECT (SELECT COUNT(*) FROM Table_1)+(SELECT COUNT(*) FROM Table_2) as total
 
Share this answer
 
v3
Comments
Karwa_Vivek 17-Jul-12 2:21am    
this will require to create a stored procedure
can this be done in a single query
StianSandberg 17-Jul-12 2:24am    
updated my question with a "one liner" :)


Try below query:

SQL
SELECT SUM(cnt) FROM (
SELECT COUNT(*) cnt FROM table_1
UNION ALL
SELECT COUNT(*) cnt FROM  table_2) tbl

 
Share this answer
 
v2
Comments
Karwa_Vivek 17-Jul-12 2:30am    
thanks
ssd_coolguy 17-Jul-12 2:32am    
Glad it helps...
StianSandberg 17-Jul-12 2:43am    
This solution wont work. You'll have to add an alias after the query:
SELECT SUM(cnt) FROM (
SELECT COUNT(*) cnt FROM table_1
UNION ALL
SELECT COUNT(*) cnt FROM table_2) tbl <---
ssd_coolguy 17-Jul-12 2:51am    
hei AlluvialDeposit..
yes you are right.. it's my mistake.. i tried it on oracle.. ;)
anyway. i modified it.
thank you very much.. :)
Hello dude use this query.........

SQL
SELECT
(SELECT Count(*) FROM tab1  ) +
(SELECT Count(*) FROM tab2   )  as new_columnname


otherwise u will use this code as like ............]


SQL
SELECT SUM(Coun)as Total FROM (
SELECT COUNT(*) Coun FROM tab1    
UNION ALL
SELECT COUNT(*)  Coun  FROM  tab2   ) tbl
 
Share this answer
 
v2
Try this :-


SQL
Select SUM(CNT) From (
Select COUNT(*) CNT From T1
UNION ALL
Select COUNT(*) CNT From  T2)






Yatin Chauhan
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900