创建一个聚合函数,该函数返回与最大column2值关联的column1值

问题描述 投票:1回答:1

我需要创建一个聚合函数。例如,MAX(列)返回已解析行的最大列值。我的新函数LAST_ALERT_VALUE(列)应该返回具有最大receive_time的行的列值。

例如:如果我有:

| severity       | reception_time          |
|----------------+-------------------------|
| 1              + 2016-07-04 00:00:00.000 |
| 3              + 2016-09-04 00:00:00.000 |
| 4              + 2016-08-04 00:00:00.000 |
| 2              + 2016-11-04 00:00:00.000 |
| 5              + 2016-10-04 00:00:00.000 |

那么LAST_ALERT_VALUE(严重性)应该返回2

我这是我的代码:

CREATE OR REPLACE FUNCTION max_reception_time(time1 anyelement, time2 anyelement) RETURNS anyelement AS $$
BEGIN
if time1 > time2 then
    return time1;
end if;
return time2;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION last_alert_value_func(p_reception_time anyelement) RETURNS anyelement AS $$
BEGIN
SELECT severity FROM report.report_table AS r WHERE r.reception_time = p_reception_time;
END;
$$ LANGUAGE plpgsql;


CREATE AGGREGATE last_alert_value(anyelement)
(
    sfunc = max_reception_time,
    stype = anyelement,
    finalfunc = last_alert_value_func
);

select last_alert_value(severity) from report.report_table;

我有错误:ERROR:运算符不存在:没有时区的时间戳= alertseverityenum

如何使last_alert_value(严重性)有效?我也想把其他列作为参数给last_alert_value,我怎么能这样做?

postgresql aggregate-functions postgresql-8.4
1个回答
2
投票

你的聚合是没有意义的,因为你可以

select severity
from report_table
order by reception_time desc
limit 1;

假设这只是具有多个参数的自定义聚合的示例,则解决方案可能如下所示:

create or replace function max_reception_time(state_rec report_table, severity int, reception_time timestamp) 
returns report_table language sql as $$
    select case 
        when state_rec.reception_time > reception_time
        then state_rec
        else (severity, reception_time)::report_table
        end;
$$;

create or replace function max_reception_time_final(state_rec report_table)
returns int language sql as $$
    select state_rec.severity
$$;

create aggregate last_alert_value(severity int, reception_time timestamp)
(
    sfunc = max_reception_time,
    stype = report_table,
    finalfunc = max_reception_time_final
);

select last_alert_value(severity, reception_time)
from report_table t;

请注意,我使用report_table作为状态数据类型。您可以改为创建复合类型。

Working code in rextester.

© www.soinside.com 2019 - 2024. All rights reserved.