sql—如何根据列中的值获取所有表的记录数?

yquaqz18  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(313)

我在oracle中有一个表列表,其值如下
参考表1

System(Col 1)  Description(Col 2) 
ABC             abba
PQR             puqar
XYZ             end
ABC             abba
ABC             abba
PQR             puqar

我想按系统(第1列)检索以ref开头的所有表的记录计数

TableName    ABC   PQR   XYZ
REF_table1   3      2     1
REF_table2   6      2     5
REF_table3   4      3     7

我试过一个问题,但没有成功

DECLARE
   nbr NUMBER := 0;
   total NUMBER := 0;
   stmt VARCHAR2(100):= 'SELECT COUNT(System),System FROM ';
BEGIN
   -- Iterate over all tables that fit your criteria
   FOR i IN (SELECT table_name FROM all_tables t WHERE /*t.owner = '#####' and*/ t.table_name LIKE 'REF_%' and t.owner ='someone') LOOP
      nbr := 0;
      EXECUTE IMMEDIATE stmt || i.table_name INTO nbr;
      total := total + nbr;
   END LOOP;
   dbms_output.put_line('total : '||total);
END;
evrscar2

evrscar21#

包含pivot子句的select语句,pivot子句由具有名称的列组成 col1 , col2 以及 col3 可能很适合你的情况。这样,您就可以通过数组变量()的贡献,在动态查询中循环这些列及其索引 col OWA.NC_ARR ) :

SQL > SET SERVEROUTPUT ON
SQL > DECLARE
        col   OWA.NC_ARR;
        total INT := 0;   
        stmt  VARCHAR2(4000):= 
          ' PIVOT
            (
              COUNT(*) FOR System IN ( ''ABC'' AS COL1, ''PQR'' AS COL2, ''XYZ'' AS COL3 )
            )';
BEGIN
   DBMS_OUTPUT.PUT_LINE('TableName    ABC   PQR   XYZ   Total');  
   FOR i IN (SELECT table_name 
               FROM user_tables 
              WHERE table_name LIKE 'REF_%'
              ORDER BY table_name ) 
   LOOP
      DBMS_OUTPUT.PUT(RPAD(i.table_name,13,' '));
    FOR j IN 1..3 LOOP
      EXECUTE IMMEDIATE 'SELECT COL'|| j ||' FROM ' || i.table_name ||stmt INTO col(j);
      DBMS_OUTPUT.PUT(RPAD(col(j),6,' '));

      total := total + col(j);
    END LOOP;
      DBMS_OUTPUT.PUT_LINE(total);
      total := 0;      
   END LOOP;
END;
/

演示

相关问题