获取架构中所有表中相同字段的最大值

Get max value of same field in all tables in schema

我在一个架构中有 10 个 table,它们都有一个 'measurementdatetime' 字段。我正在尝试编写一个脚本,该脚本将为每个 table return 一行显示每个 table 名称和最大测量日期时间。

我觉得应该这样编码,但我想不出确切的语法

    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

我收到“错误关系 my_tablename1 不存在”

(另外:是否可以将其编译为视图?& 如果可以,如果视图的前面 'fieldnames' 是动态的,如何对其进行编码?)

您必须使用 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();