我在一个模式中有10个表,它们都有一个“measurementdatetime”字段。我正在尝试编写一个脚本,它将为每个表返回一行,显示每个表的表名和最大度量日期时间。
我想应该像这样编码,但我无法找出确切的语法

    SELECT table_name AS table_full_name,
    MAX ( table_name || '.measurementdatetime'  ) AS max_timestamp
    FROM information_schema.tables
    WHERE table_schema = 'temp_work_w_roof'
    GROUP BY tables.table_name
    ORDER BY pg_total_relation_size('"' ||  table_name || '"') DESC

我得到了“错误关系MyOTabLeNAM1不存在”
(还有:是否可以将其编译为视图?&如果是这样,如果视图的前面的“字段名”是这样动态的,那么如何对它们进行编码呢?)

最佳答案

您必须使用plpgsql language dynamic command,例如:

create or replace function get_max_measurementdatetime()
returns table (table_name text, max_value timestamp)
language plpgsql as $$
declare
    r record;
begin
    for r in
        select i.table_name, i.table_schema
        from information_schema.tables i
        where table_schema = 'temp_work_w_roof'
        and table_type = 'BASE TABLE'
    loop
        execute format (
            'select max(measurementdatetime) from %I.%I',
            r.table_schema, r.table_name)
        into max_value;
        table_name := r.table_name;
        return next;
    end loop;
end $$;

select *
from get_max_measurementdatetime();

10-08 03:56