Select count(*) from multiple tables

2019-01-03 00:55发布

How can I select count(*) from two different tables (call them tab1 and tab2) having as result:

Count_1   Count_2
123       456

I've tried this:

select count(*) Count_1 from schema.tab1 union all select count(*) Count_2 from schema.tab2

But all I have is:

Count_1
123
456

标签: sql oracle count
18条回答
贪生不怕死
2楼-- · 2019-01-03 01:49

Other slightly different methods:

with t1_count as (select count(*) c1 from t1),
     t2_count as (select count(*) c2 from t2)
select c1,
       c2
from   t1_count,
       t2_count
/

select c1,
       c2
from   (select count(*) c1 from t1) t1_count,
       (select count(*) c2 from t2) t2_count
/
查看更多
▲ chillily
3楼-- · 2019-01-03 01:49

Here is from me to share

Option 1 - counting from same domain from different table

select distinct(select count(*) from domain1.table1) "count1", (select count(*) from domain1.table2) "count2" 
from domain1.table1, domain1.table2;

Option 2 - counting from different domain for same table

select distinct(select count(*) from domain1.table1) "count1", (select count(*) from domain2.table1) "count2" 
from domain1.table1, domain2.table1;

Option 3 - counting from different domain for same table with "union all" to have rows of count

select 'domain 1'"domain", count(*) 
from domain1.table1 
union all 
select 'domain 2', count(*) 
from domain2.table1;

Enjoy the SQL, I always do :)

查看更多
不美不萌又怎样
4楼-- · 2019-01-03 01:49
    select 
    t1.Count_1,t2.Count_2
    from 
(SELECT count(1) as Count_1 FROM tab1) as t1, 
(SELECT count(1) as Count_2 FROM tab2) as t2
查看更多
相关推荐>>
5楼-- · 2019-01-03 01:50

Just because it's slightly different:

SELECT 'table_1' AS table_name, COUNT(*) FROM table_1
UNION
SELECT 'table_2' AS table_name, COUNT(*) FROM table_2
UNION
SELECT 'table_3' AS table_name, COUNT(*) FROM table_3

It gives the answers transposed (one row per table instead of one column), otherwise I don't think it's much different. I think performance-wise they should be equivalent.

查看更多
叛逆
6楼-- · 2019-01-03 01:51

As additional information, to accomplish same thing in SQL Server, you just need to remove the "FROM dual" part of the query.

查看更多
成全新的幸福
7楼-- · 2019-01-03 01:52
--============= FIRST WAY (Shows as Multiple Row) ===============
SELECT 'tblProducts' [TableName], COUNT(P.Id) [RowCount] FROM tblProducts P
UNION ALL
SELECT 'tblProductSales' [TableName], COUNT(S.Id) [RowCount] FROM tblProductSales S


--============== SECOND WAY (Shows in a Single Row) =============
SELECT  
(SELECT COUNT(Id) FROM   tblProducts) AS ProductCount,
(SELECT COUNT(Id) FROM   tblProductSales) AS SalesCount
查看更多
登录 后发表回答