更新PostgreSQL中的下限和上限

时间:2017-06-06 08:47:05

标签: sql postgresql postgis postgresql-9.5

我的PostgreSQL 9.5数据库中有一个表(12行),有两列ID和几何。 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

有更好的方法吗?任何指针都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

起初我想在这里使用窗口函数,但后来我意识到你不需要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来避免在窗口函数中列出案例:

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