插入后合并可服从的非重叠范围

时间:2019-09-25 01:25:17

标签: sql postgresql

假设您有一个这样的表:

+-------+-----+------+
| start | end | size |
+-------+-----+------+
|     0 |  9  |   10 |
|    12 |  12 |    1 |
|    30 |  50 |   21 |
+-------+-----+------+

然后插入(11, 11, 1),以便现在有了(假设start列上的索引:

+-------+-----+------+
| start | end | size |
+-------+-----+------+
|     0 |  9  |   10 |
|    11 |  11 |    1 |
|    12 |  12 |    1 |
|    30 |  50 |   21 |
+-------+-----+------+

插入此行后,如何有效地合并两个连续范围以最终得到这样的表:

+-------+-----+------+
| start | end | size |
+-------+-----+------+
|     0 |  9  |   10 |
|    11 |  12 |    2 |
|    30 |  50 |   21 |
+-------+-----+------+

编辑:
-对不起,我弄乱了桌子,现在应该把它们修好
-插入后我想就地修改表

1 个答案:

答案 0 :(得分:0)

使用以下代码

select min("start") as "Start",max("end") as "End",sum("size") as "Size"
from "Test112" group by "size"
order by "Start"

0;10;11
11;12;2
30;50;21