sql count使用单个查询从多个表中记录

时间:2012-04-17 05:23:03

标签: sql oracle

我有一个表格列表,例如:

mytableA
mytableB
mytableC

表格都有相同的列(时间戳)。

我可以分别对每张桌子进行统计:

select count(*) from mytableA where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000';
select count(*) from mytableB where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000';
select count(*) from mytableC where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000';

如何在一个查询中将其合并?有一个简单的方法吗?

预期结果:

MyTableName     MyCnt
-----------     -----
mytableA        121
mytableB        78
mytableC        2345

7 个答案:

答案 0 :(得分:4)

您无法直接使用where table in (myTableA, myTableB, etc)之类的查询来执行此操作 但你可以为union all解决方案做好准备:

select MyTableName, count(*)
FROM(
  select 'myTableA' MyTableName, timestamp from mytableA 
  union all
  select 'myTableB', timestamp  from mytableB  
  union all
  select 'myTableA', timestamp  from mytableC  
)
WHERE timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000'
GROUP BY MyTableName;

答案 1 :(得分:2)

SELECT  (
    SELECT COUNT(*)
    FROM   table1
    ) AS tot1,
    (
    SELECT COUNT(*)
    FROM   table2
    ) AS tottab2,
    (
    SELECT COUNT(*)
    FROM   table3
    ) AS tottab3

答案 2 :(得分:1)

我不确定Oracle,在SQLserver中你可以这样做,

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

<强>更新 或者像这样,

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

OR,

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

答案 3 :(得分:1)

select 'myTableA' MyTableName, count(*) MyCnt from mytableA where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000'
union all
select 'myTableB', count(*) from mytableB where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000'
union all
select 'myTableC', count(*) from mytableC where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000';

答案 4 :(得分:0)

这个怎么样?

SELECT 
     a, b, c 
FROM 
     (select count(*) from mytableA where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000') AS a, 
     (select count(*) from mytableB where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000') AS b, 
     (select count(*) from mytableC where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000') AS c

不知道这是否有效:/

答案 5 :(得分:0)

试试这个

select 'mytableA' as tablename, count(*) from mytableA where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000'
union all
select 'mytableB' as tablename , count(*) from mytableB where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000'
union all
select'mytableB' as tablename , count(*) from mytableC where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000'

答案 6 :(得分:0)

使用Oracle 11gR2:

select     
  (select count(*) from mytableA where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000') tabA,
  (select count(*) from mytableB where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000') tabB,
  (select count(*) from mytableC where timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000') tabC
from dual;

结果:

tabA| tabB| tabC
----|-----|-----
 121|   78| 2345