2010-12-22 74 views
4

有沒有辦法從所有行中減去第一個選定行的值?所以,如果我有SQL從所有選定行減去第一行

t = 1, v = 500 
t = 2, v = 800 
t = 3, v = 1200 

我會得到

t = 1, v = 0 
t = 2, v = 300 
t = 3, v = 700 

我一直在尋找一種便攜式解決方案,但一個Postgres的解決方案可以使用原來的:-) 謝謝。

回答

5
SELECT v - FIRST_VALUE(v) OVER (ORDER BY t) 
FROM mytable 
ORDER BY 
     t 
1

像這樣的東西可能工作

SELECT mt2.t, mt2.v - mt1.v AS v 
FROM MyTable mt1 
CROSS JOIN MyTable mt2 
WHERE mt1.t = 1 
0

大多數便攜式的方式,而無需使用窗口功能:

select v - first 
from 
    mytable, 
    (select v as first from mytable order by t limit 1) as inner 
order by t 
+0

LIMIT 1是一樣便攜的窗口功能;) – 2010-12-22 21:07:59

相關問題