简体   繁体   中英

oracle sql return count along with other columns

This question is about oracle 12.1.0.2 on aix 7.2.

I have 5 tables and I want to do this query:

select owner, table_name, LAST_DDL_TIME, count(*) 
from dba_objects
where owner = 'WAREHOUSE' 
and OBJECT_NAME in ('table1','table2','table3','table4','table5') 
and OBJECT_TYPE = 'TABLE'

I want the 3 columns in the select clause and the actual count of the 5 tables. I want to do this in one query if possible.

If I add group by owner, table_name, LAST_DDL_TIME it will return a count of 1 for each row.

So my result set I want will look like this:

OWNER       OBJECT_NAME     LAST_DDL_TIME           COUNT(*)
SCHEMA1     TABLE1          7/9/2016 3:47:27 PM     5932158
SCHEMA1     TABLE2          7/9/2016 3:47:31 PM     432
SCHEMA1     TABLE3          7/9/2016 3:47:15 PM     958741
SCHEMA1     TABLE4          7/9/2016 3:47:31 PM     11298
SCHEMA1     TABLE5          7/9/2016 3:47:15 PM     3645873385

You can use some XML magic to do dynamic SQL inside plain SQL query.

select owner, object_name, LAST_DDL_TIME, 
       to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from "'||owner||'"."'||object_name||'"')),'/ROWSET/ROW/C')) as count
from dba_objects
where owner = 'WAREHOUSE' 
and OBJECT_NAME in ('table1','table2','table3','table4','table5') 
and OBJECT_TYPE = 'TABLE'

A hack, using only plain SQL and hard-coded owner and table names, is shown below. It shouldn't be used unless this is a one-in-an-organization's-lifetime requirement.

For testing, I used SYS and a few tables in the SYS schema on my machine. If you find this helpful, you can adapt it for your situation.

with 
    counts (table_name, ct) as (
      select 'ACCESS$'                 , count(*) from SYS.ACCESS$                union all
      select 'ALERT_QT'                , count(*) from SYS.ALERT_QT               union all
      select 'APPLY$_CHANGE_HANDLERS'  , count(*) from SYS.APPLY$_CHANGE_HANDLERS union all
      select 'APPLY$_CONF_HDLR_COLUMNS', count(*) from SYS.APPLY$_CONF_HDLR_COLUMNS
    )
select o.owner, o.object_name, o.last_ddl_time, c.ct
from   dba_objects o
       inner join
       counts c
       on o.object_name = c.table_name
where  o.object_type = 'TABLE'
  and  o.owner = 'SYS'
;


OWNER    OBJECT_NAME               LAST_DDL_T         CT
-------- ------------------------- ---------- ----------
SYS      ACCESS$                   2014-05-29      34698
SYS      ALERT_QT                  2014-05-29          0
SYS      APPLY$_CHANGE_HANDLERS    2014-05-29          0
SYS      APPLY$_CONF_HDLR_COLUMNS  2014-05-29          0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM