4

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

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
4

7 回答 7

8
SELECT  (
    SELECT COUNT(*)
    FROM   table1
    ) AS tot1,
    (
    SELECT COUNT(*)
    FROM   table2
    ) AS tottab2,
    (
    SELECT COUNT(*)
    FROM   table3
    ) AS tottab3
于 2012-04-17T05:29:42.380 回答
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;
于 2012-04-17T05:47:17.717 回答
2

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

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

更新: 或者像这样,

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

或者,

(select count(*) from table1) union (select count(*) from table2)
于 2012-04-17T05:26:25.360 回答
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';
于 2012-04-17T05:28:39.647 回答
1

使用 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
于 2013-06-14T19:59:59.703 回答
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'
于 2012-04-17T05:28:42.163 回答
-3

这个怎么样?

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

不知道这是否有效:/

于 2012-04-17T05:28:08.897 回答