Postgresql 创建一个聚合函数,该函数返回与最大column2值关联的column1值
我需要创建一个聚合函数。例如,MAX(column)返回解析行中的MAX列值。我的新函数LAST_ALERT_VALUE(column)应该返回接收时间最大的行的列值 例:如果我有:Postgresql 创建一个聚合函数,该函数返回与最大column2值关联的column1值,postgresql,aggregate-functions,postgresql-8.4,Postgresql,Aggregate Functions,Postgresql 8.4,我需要创建一个聚合函数。例如,MAX(column)返回解析行中的MAX列值。我的新函数LAST_ALERT_VALUE(column)应该返回接收时间最大的行的列值 例:如果我有: | severity | reception_time | |----------------+-------------------------| | 1 + 2016-07-04 00:00:00.000 | | 3 + 2016
| 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 |
最后一个警报值(严重性)应返回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;
我有一个错误:错误:运算符不存在:没有时区的时间戳=alertseverityenum
如何使上次警报值(严重性)正常工作?我还想把其他列作为最后一个警报值的参数,我该怎么做呢?你的聚合是没有意义的,因为你可以
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\u table
作为状态数据类型。您可以改为创建复合类型