12

我正在使用 redshift 并想创建一个逗号分隔的列列表。我正在尝试使用以下方法从信息架构中获取列名listagg

SELECT  
listagg(column_name,',') within group (order by ordinal_position) 
FROM    information_schema.columns
WHERE   table_schema = 'my_schema'
AND     table_name = 'my table';

我收到以下错误:

[Amazon](500310) Invalid operation: Function (listagg(text,text)) must be applied on at least one user created tables;
4

2 回答 2

4

这是我测试过的解决方法..

select listagg(column_name, ', ') within group (order by column_name)
from 
(
    select  
        a.attname::varchar as column_name, typname::varchar as data_type
    from
        pg_type t, 
        pg_attribute a,
        pg_class c,
        pg_namespace ns,
        (select top 1 1 from my_schema.my_table)
    where 
        t.oid=a.atttypid
        and a.attrelid = c.oid
        and c.relnamespace = ns.oid
        and typname NOT IN ('oid','xid','tid','cid')
        and attname not in ('deletexid', 'insertxid')
        and trim(relname) = 'my_table'
        and ns.nspname = 'my_schema'
)
于 2019-12-24T05:32:10.967 回答
1

虽然这没有回答如何在 information_schema 上应用 listagg,但我可以推荐一种在 pg 目录表上使用 listagg 的替代方法。

试试这个:

SELECT DISTINCT listagg(attname, ',') WITHIN GROUP (ORDER BY a.attsortkeyord) AS "columns"
FROM pg_attribute a, pg_namespace ns, pg_class c, pg_type t, stv_tbl_perm p, pg_database db
WHERE t.oid=a.atttypid AND a.attrelid=p.id AND ns.oid = c.relnamespace AND db.oid = p.db_id AND c.oid = a.attrelid
AND typname NOT IN ('oid','xid','tid','cid')
AND ns.nspname = 'my_schema'
AND RTRIM(name) = 'my table'
于 2016-04-27T20:59:39.447 回答