I need to create an aggregate function. For example, MAX(column) returns the max column values from the parsed rows. My new function LAST_ALERT_VALUE(column) should return the column value of the row which has the biggest reception_time.
Ex: if i have:
| 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 |
then LAST_ALERT_VALUE(severity) should return 2
I Here is my code:
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;
I have the error: ERROR: operator does not exist: timestamp without time zone = alertseverityenum
How can I make last_alert_value(severity) works ? I also want to can give as argument others columns to last_alert_value, how can I do that ?
Your aggregate is pointless because you can just
Assuming this is only an example of a custom aggregate with more than one argument, a solution may look like this:
Note, that I have used
report_tableas the state data type. You could create a composite type instead.Working code in rextester.