I've created an aggregate function that aggregates all values into an array based on an index.
The index represents the position in the array.
The function is this:
CREATE AGGREGATE array_agg_index(anyelement, integer) (
SFUNC=function_array_agg_index,
STYPE=anyarray
);
create or replace function function_array_agg_index(
prev anyarray,
new anyelement,
idx integer)
returns anyarray as
$BODY$
BEGIN
IF prev IS NULL THEN prev[1] = null; END IF;
prev[idx] = new;
RETURN prev;
END;
$BODY$
LANGUAGE plpgsql;
Now I have to extend this function to return an array but take into account a second index.
Example:
PERSON_ID | INDEX_1 | INDEX_2 | VALUE |
---|---|---|---|
1 | 1 | 1 | A |
1 | 1 | 2 | B |
1 | 2 | 1 | C |
1 | 2 | 2 | D |
The "old" function would return AC
.
The new function should return AC
and BD
.
This is how the old function is called:
SELECT PERSON_ID, array_agg_index(VALUE, INDEX_1) FROM PERSON GROUP BY (PERSON_ID);
Making a new function rather using the existing seems like solving the problem at the wrong level. You just need to use the old function twice in the query:
SELECT PERSON_ID, array_agg_index(VALUE, INDEX_1) thing1, array_agg_index(VALUE, INDEX_2) thing2 FROM PERSON GROUP BY (PERSON_ID);
person_id | thing1 | thing2
-----------+--------+-------
1 | {B,D} | {C,D}
This doesn't return what you said you wanted, but neither does the original so I think you just messed up your example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.