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

时间:2016-11-15 11:14:47

标签: postgresql max information-schema

我在一个架构中有10个表,它们都有一个测量日期'领域。我正在尝试编写一个脚本,该脚本将为每个表返回一行,显示每个表的tablename和max 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不存在'

(另外:是否可以将其编译为视图?&若然,如果他们像这样动态,如何对视图的前面的字段名进行编码?)

1 个答案:

答案 0 :(得分:2)

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