问题:获取模式中所有表中相同字段的最大值

我在一个模式中有 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

我得到'错误关系 my_tablename1 不存在'

(另外:是否可以将其编译为视图?如果可以,如果它们是动态的,如何编码视图的前面的“字段名”?)

解答

您必须使用plpgsql 语言动态命令,例如:

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();
Logo

PostgreSQL社区为您提供最前沿的新闻资讯和知识内容

更多推荐