2017-06-06 80 views
1

我在我的PostgreSQL 9.5數據庫中有一個表(12行),它有兩列ID和幾何。來自PgAdmin3的表格結構是:更新PostgreSQL的下限和上限

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 

有沒有更好的方法來做到這一點?任何指針將高度讚賞。

+0

請將表格定義添加到帖子 –

+0

@VaoTsun:請參閱編輯。從pgAdmin3添加了表結構。 –

回答

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 
+0

這個工作,但請注意,我需要更新my_table,即根據ID生成角度,三角形的下限和上限。這就是爲什麼我使用CASE語句作爲ID。或者,我需要在「g」(你提出的解決方案)和my_table之間進行連接。正確? –

+0

也許,在ID列上使用窗口函數可能是更好的方法? –

+0

是的 - 如果角度不增長30,則需要將id綁定到角度值,然後使用lead()或lag()over() –