4

I have a list of tables for example:

mytableA
mytableB
mytableC

The tables all have same column (timestamp).

I can do a count on each table individually:

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';

How can I combine this in one single query? Is there an easy way?

Expected Results:

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 に答える
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 に答える