更新 PostgreSQL 中的下限和上限

Update lower and upper bounds in PostgreSQL

我的 PostgreSQL 9.5 数据库中有一个 table(12 行),其中有两列 ID 和 geometry。 Table 来自 PgAdmin3 的结构是:

CREATE TABLE public.my_table
(
id integer,
geom geometry
)

几何表示从真北开始的三角形,ID 为 1,依此类推。每行的 ID 都是唯一的,即 1 - 12。基于此 ID,我正在尝试更新角度及其下限和上限。我的方法是:

Select
id,
Case    when id = 1 then 30
        when id = 2 then 60
        when id = 3 then 90
        when id = 4 then 120
        when id = 5 then 150 
        when id = 6 then 180
        when id = 7 then 210 
        when id = 8 then 240 
        when id = 9 then 270
        when id = 10 then 300
        when id = 11 then 330
        when id = 12 then 360
end as angle,
case    when id = 1 then lower(numrange(0, 30))
        when id = 2 then lower(numrange(30, 60))
        when id = 3 then lower(numrange(60, 90))
        when id = 4 then lower(numrange(90, 120))
        when id = 5 then lower(numrange(120, 150))
        when id = 6 then lower(numrange(150, 180))
        when id = 7 then lower(numrange(180, 210))
        when id = 8 then lower(numrange(210, 240))
        when id = 9 then lower(numrange(240, 270))
        when id = 10 then lower(numrange(270, 300))
        when id = 11 then lower(numrange(300, 330))
        when id = 12 then lower(numrange(330, 360))
end as lb
from my_table

有更好的方法吗?任何指针将不胜感激。

起初我想在这里使用 window 函数,但后来我意识到您不需要 my_table 中的任何列。尝试:

已更新以反映 OP 的注释(请注意,您需要明确定义最低边界 - 这里我使用了零)

t=# with p as (select id,angle from generate_series(30,360,30) with ordinality as g(angle,id)) select *,coalesce(lag(angle) over (order by id),0) lb from p;
 id | angle | lb
----+-------+-----
  1 |    30 |   0
  2 |    60 |  30
  3 |    90 |  60
  4 |   120 |  90
  5 |   150 | 120
  6 |   180 | 150
  7 |   210 | 180
  8 |   240 | 210
  9 |   270 | 240
 10 |   300 | 270
 11 |   330 | 300
 12 |   360 | 330
(12 rows)

更新 重写 OP 查询我将使用 CTE 来避免在 window 函数中列出案例:

t=# with a as (Select
id,
Case    when id = 1 then 30
        when id = 2 then 60
        when id = 3 then 90
        when id = 4 then 120
        when id = 5 then 150
        when id = 6 then 180
        when id = 7 then 210
        when id = 8 then 240
        when id = 9 then 270
        when id = 10 then 300
        when id = 11 then 330
        when id = 12 then 360
end as angle
from my_table)
select *,coalesce(lag(angle) over (order by id),0)
from a;
 id | angle | coalesce
----+-------+----------
  1 |    30 |        0
  2 |    60 |       30
  3 |    90 |       60
  4 |   120 |       90
  5 |   150 |      120
  6 |   180 |      150
  7 |   210 |      180
  8 |   240 |      210
  9 |   270 |      240
 10 |   300 |      270
 11 |   330 |      300
 12 |   360 |      330
(12 rows)

Time: 0.462 ms