在一个SQL中打印来自多个表的计数

时间:2014-10-12 05:40:11

标签: sql oracle

数据库版本:11.1.2.3.0

我正在使用以下SQL:

SELECT tab_nam, cnt  
FROM  
(  
SELECT 'Tab1' "tab_nam", COUNT(1) "cnt" FROM Tab1  
UNION  
SELECT 'Tab2' "tab_nam", COUNT(1) "cnt" FROM Tab2  
);  

TAB_NAM   CNT  
-------   ------  
Tab1      23  
Tab2      10  

CREATE TABLE Tab1 (id NUMBER, name VARCHAR2(100));
CREATE TABLE Tab2 (id NUMBER, name VARCHAR2(100));

有没有其他方法可以获得上述形式的输出? 我想仅以上面的格式获取结果集而不是水平..

不同SQL的原因:我无法将SQL输出打印到HTML。使用的格式:

PRO <h3>Table Count</h3>
PRO <table>
PRO <tr>
PRO <th>Table Name</th>
PRO <th>Count</th>
PRO </tr>
SELECT '<tr>'||
'<td class="left">'||"tab_name"||'</td>'||
'<td class="center">'||"cnt"||'</td>'||
'</tr>'
FROM  (
SELECT 'Tab1' "tab_name", COUNT(1) "cnt" FROM Tab1
UNION
 SELECT 'Tab2' "tab_name", COUNT(1) "cnt" FROM Tab2);
PRO </table>

蒂亚..

1 个答案:

答案 0 :(得分:3)

有几种方法可以在单个查询中查找SOME / ALL表的计数。例如,让我们说我想从模式中的所有表中获取行数&#39; SCOTT&#39;。

1.使用SQL

SQL> column table_name format A15;
SQL> SELECT table_name,
  2    to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from '
  3    ||owner
  4    ||'.'
  5    ||table_name)),'/ROWSET/ROW/C')) AS COUNT
  6  FROM all_tables
  7  WHERE owner = 'SCOTT'
  8  /

TABLE_NAME           COUNT
--------------- ----------
DEPT                     4
EMP                     14
BONUS                    0
SALGRADE                 5

SQL>

2.收集了100%的统计信息

SQL> EXEC DBMS_STATS.gather_schema_stats('SCOTT', estimate_percent => 100);

PL/SQL procedure successfully completed.

SQL> column owner format A10;
SQL> select owner, table_name, num_rows, sample_size, last_analyzed from all_tables where owner = 'SCOTT';

OWNER      TABLE_NAME        NUM_ROWS SAMPLE_SIZE LAST_ANAL
---------- --------------- ---------- ----------- ---------
SCOTT      DEPT                     4           4 12-OCT-14
SCOTT      EMP                     14          14 12-OCT-14
SCOTT      BONUS                    0           0 12-OCT-14
SCOTT      SALGRADE                 5           5 12-OCT-14

SQL>

3.使用PL / SQL

SQL> SET serveroutput ON;
SQL> DECLARE
  2    var_count NUMBER;
  3  BEGIN
  4    FOR i IN
  5    (SELECT table_name, owner FROM all_tables WHERE owner = 'SCOTT'
  6    )
  7    LOOP
  8      EXECUTE IMMEDIATE 'select count(*) from ' || i.table_name INTO var_count;
  9      dbms_output.put_line(i.table_name ||' - '|| var_count);
 10    END LOOP;
 11  END;
 12  /
DEPT - 4
EMP - 14
BONUS - 0
SALGRADE - 5

PL/SQL procedure successfully completed.

SQL>

但SQL方法更简单,不是吗?