简体   繁体   English

SQL 中的 LISTAGG 用法

[英]LISTAGG usage in SQL

I am trying to pull the schema,table name,no.我正在尝试提取架构,表名,否。 of records in it,count of columns,names of the columns(comma separated) and name of the primary key columns(comma separated) in a single query.单个查询中的记录数、列数、列名(逗号分隔)和主键列名(逗号分隔)。

SELECT t.owner, 
       t.table_name, 
       t.num_rows,
       count(*),
       listagg(c.column_name,',') within group (order by c.column_name)columnlist,
       listagg(a.column_name,',') within group (order by a.column_name,a.constraint_name)keycolumns
FROM all_tables t
       left join
       all_tab_columns c on t.table_name = c.table_name
       left join
       all_cons_columns a on c.table_name = a.table_name
       inner join 
       all_constraints d on a.constraint_name = d.constraint_name     
where c.table_name = 'PROCESS_LOG'
and d.constraint_type = 'P'
and num_rows IS NOT NULL
GROUP  BY t.owner, 
          t.table_name,
          --c.column_name
          t.num_rows
ORDER BY t.num_rows DESC;

The issue is its fetching repetitive column names in the comma separated lists and the no of columns is not correctly fetched.问题是它在逗号分隔的列表中获取重复的列名,并且没有正确获取列数。 Could you please help me fix this?你能帮我解决这个问题吗?

Output:输出:

OWNER | TABLE_NAME  | NUM_ROWS | COUNT(*) | COLUMNLIST                      | KEYCOLUMNS
------+-------------+----------+----------+---------------------------------+----------------
ABC   | PROCESS_LOG |          |       16 | A,A,A,A,B,B,B,B,C,C,C,C,D,D,D,D | C,C,C,C,D,D,D,D

Expected:预期的:

OWNER | TABLE_NAME  | NUM_ROWS | COUNT(*) | COLUMNLIST | KEYCOLUMNS
------+-------------+----------+----------+------------+-----------
ABC   | PROCESS_LOG |          |        4 | A,B,C,D    | C,D

Thanks,谢谢,

First get your aggregates (column count and list plus key column list) separately, then join.首先分别获取您的聚合(列数和列表加键列列表),然后加入。

with tableinfo as
(
  select 
    t.owner, 
    t.table_name, 
    t.num_rows,
    count(*) as num_cols,
    listagg(c.column_name, ',') within group (order by c.column_name) as columnlist
  from all_tables t
  join all_tab_columns c on c.owner = t.owner and c.table_name = t.table_name
  group by t.owner, t.table_name, t.num_rows
)
, pkinfo as
(
  select
    c.owner,
    c.table_name,
    listagg(cc.column_name, ',') within group (order by cc.position) as keycolumns
  from all_constraints c
  join all_cons_columns cc on cc.owner = c.owner and cc.constraint_name = c.constraint_name   
  where c.constraint_type = 'P'
  group by c.owner, c.table_name
)
select *
from tableinfo t
left join pkinfo pk using (owner, table_name)
where t.table_name = 'PROCESS_LOG'
order by t.num_rows desc;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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