khajlk
I have a question based on [this fiddle](https://dbfiddle.uk?rdbms=postgres_9.5&fiddle=acb59b827302500cb9cf10e512fa997a), but my question is different and the corresponding sample data is as follows (updated the sample data to add `id` column for ordering within each group):

<>https://dbfiddle.uk/?rdbms=postgres_9.5&fiddle=4689efc43b8f2b40f5a3c94b367c8b1c

For each group `grp`, I would like to merge/combine the values of `low,` `high` based on `avg` using `axis_1` and `axis_2` as controls.

For each `grp`, if the difference between `avg` values (the preceding and the succeeding ones) is zero (same value) then merge all such rows (with `low` of the first row to the `high` of the last merged row). The merging/combining is not allowed across the `axes` values (`axis_1` and `axis_2`), that is, rows should not be merged crossing over the axes values. The `low` and `high` of the merged rows need to be in order as expected output.

The expected output (`grp` and `text/string array`) is as follows. The `merged_row array `is in the format `low,high,avg...` (for all possible "sub-groups" in a `grp`).

```
grp		merged_row
1		292,112,18.8
6		182,212,0.0,212,272,0.0,272,332,21.4,332,32,0.0
7		275,335,0.0,335,35,0.0,35,155,21.2,
```

Can someone help me to achieve the expected output?
Top Answer
Jack Douglas
You need several steps to do this:

1. split groups and islands (modified to break on axis match)
2. get and combine the first and last rows in each subgroup/island
3. aggregate the results for the islands into a single array per group

This is the final query — visit the fiddle to see each step building up:

<>https://dbfiddle.uk/?rdbms=postgres_9.5&fiddle=ae15b71d0fef1be3b1599d44e629c506&hide=15

Enter question or answer id or url (and optionally further answer ids/urls from the same question) from

Separate each id/url with a space. No need to list your own answers; they will be imported automatically.