SQL从所有选定的行中减去第一行

时间:2010-12-22 17:39:56

标签: sql postgresql

有没有办法从所有行中减去第一个选定行的值?所以,如果我有

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解决方案的工作原理相同:-) 谢谢。

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:1)

这样的事可能有效

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

答案 2 :(得分:0)

不使用窗口功能的最便携方式:

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