2015-08-13 25 views
0

如何獲得下一個值我有一個表A爲foolows:如果存在於PostgreSQL的

id name  nextid orderset 
19 done    4 
21 init  27  1 
24 sent-req 19  3 
27 offer-req 24  2 

orderset列給我的狀態順序:init -> offer-req -> sent-req -> done

我需要編寫一個查詢,對於給定的id,它給出了下一個狀態的id

這應該是很容易:

select id 
from A 
where orderset= (select orderset+1 from A where id=Any_Given_ID) 

,在所有情況下工作,除了最後一個ID ......因爲沒有旁邊id=19,在最後一個我想查詢返回0的情況下, 。

我想到與Max(orderset)select order+1 from A where id=Any_Given_ID做檢查,但我似乎無法使它工作。

它在查詢中可行還是必須爲此操作編寫函數?

回答

2

假設訂單是連續的,只要使用lead()

select id 
from (select coalesce(lead(id) over (order by orderset), 0) as id 
     from A 
    ) a 
where id = Any_Given_ID; 

你也可以用你的方法採用聚集。這保證返回一行:

select coalesce(max(id), 0) 
from A 
where orderset = (select orderset + 1 from A where id = Any_Given_ID); 
+0

我糊塗了......我沒有用,雖然聚結的原因(什麼東西,0),是因爲如果第一個參數存在,它總是返回他。那爲什麼它會返回0?最大(id)存在。 – John

+1

@John。 。 。如果where子句沒有匹配,則max()返回NULL。 –

+0

thx。你能解釋一下這個主要例子嗎? postgresql手冊說:「在分區內當前行之後偏移行的行返回值評估」,這不是很清楚。 – John

相關問題