I have gone through some relevant merging questions but my problem is slightly different from the existing ones. I have a table in my PostgreSQL 9.5 database containing four columns i.e., Segment (unique group), height (numeric), lower_limit (numeric) and upper_limit (numeric). The sample data is as follows:
Segment height lower_limit upper_limit
A 19.3 112 142
A 19.3 142 172
A 20.3 172 202
A 20.3 202 232
A 19.3 232 262
A 19.3 262 292
B 22.1 203 233
B 22.1 233 263
B 22.1 263 293
B 22.1 293 323
B 22.1 323 353
B 22.1 353 383
C 18.9 136 166
C 18.9 166 196
C 18.9 196 226
C 27.1 286 316
C 27.1 316 346
C 6.5 346 376
C 6.5 376 406
I need to conditionally merge rows based on the difference of height values. I would try to explain in steps:
- Starting from the first height, check if the difference between preceding and succeeding row is less or equal to 1
- If condition fulfills merge those rows with lower limit of first row and upper limit of merged row
- if all rows are merged in a group then select the most common height with lower limit of first and upper limit of last merged row
repeat this for other groups
Based on above, the desired output could be like:
Segment height lower_limit upper_limit A 19.3 112 292 B 22.1 203 383 C 18.9 136 226 C 27.1 286 346 C 6.5 346 406
Can somebody help me so that I could conditionally merge rows based on height difference values?