计算同一张表中两列的平均值

时间:2019-05-24 08:01:38

标签: postgresql

我有一个看起来像这样的表(ttable):

id    debut     fin     value
1       2        4        10
2       4        6        0
3       6        8        12

我想通过将ID n°1和3的值设置为平均值,并在某些字段(首演和鳍)上将它们设置为平均值,来更新ID n°2的值。 我想得到这个:

id    debut     fin     value
1       2        4        10
2       4        6        11
3       6        8        12

...其中id°2从10和12取平均值,因为它的初值等于id n°1鳍值(4),并且其fin值等于id n°3鳍值(6)。我正在考虑在桌子上进行自我连接,就像这样:

update ttable
    set value = 
    avg(m1 + m2) as 
    (select t1.value as m1, t3.value as m2 
  from ttable t1, ttable t2, ttable t3 where t1.fin = t2.debut and where t2.fin = t3.debut) 

但是这不起作用,因为我无法将其保存到函数中。我不知道该怎么做。 有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您可以尝试lag / lead window functions

update ttable as d
  set value = (s.lg + s.ld) / 2
from (
  select
    id,
    lag(value) over(order by id) as lg,
    lead(value) over(order by id) as ld
  from ttable
) as s
where d.id = s.id and
      d.value = 0 and
      s.lg is not null and
      s.ld is not null;

使用SQL Fiddle在线进行测试。

尝试#2:

update ttable as d
  set value = (p.value + x.value) / 2
from ttable as p, ttable as x
where p.value > 0 and
      d.value = 0 and
      x.value > 0 and
      p.fin = d.debut and
      d.fin = x.debut;

使用SQL Fiddle在线进行测试。

答案 1 :(得分:0)

我尝试了这个,它似乎可以工作,但是我想有一个更简单的方法:

update ttable as d
set value = (u.lg + v.ld) / 2
from (
select
d.id,
s.value as lg
from ttable d, ttable s
where d.fin = s.debut
) as u,
(
select
d.id,
t.value as ld
from ttable d, ttable t
where d.debut = t.fin
) as v

where d.id = u.id and
        d.id = v.id and
  d.value = 0 and
  u.lg is not null and
  v.ld is not null;