对基于ID的计算值求和

时间:2019-07-16 06:10:13

标签: sql

所以我有这样的东西:

SELECT WB.ID,
((WB.DUR+WB.DUR)*((coalesce(t.total,0)) + (coalesce(tx.total,0)))/(DURA.TOTDUR+DISTA.TOTDIST)) as X,
...
...
...

我正在尝试根据WB.ID求和X。

DURA和DISTA都联接在一起,不是数据库表(本地)。 t和tx也一样

ID  X
25  2127.480000
26  6.200000
32  47.120000
33  0.360000
33  1.550000
33  0.240000
42  49.590000
44  21.850000
52  162.670000

结果:

ID  X           SUM(X)
25  2127.480000 2127.480000
26  6.200000    6.200000
32  47.120000   47.120000
33  0.360000    2.150000
33  1.550000    2.150000
33  0.240000    2.150000
42  49.590000   49.590000
44  21.850000   21.850000
52  162.670000  162.670000

1 个答案:

答案 0 :(得分:0)

根据示例数据,使用窗口函数看起来像是一个简单的总和:

select id, 
       x, 
       sum(x) over (partition by id) as sum_x
from the_table
order by id;

如果x是另一个查询的结果,请使用派生表:

select id, x, 
       sum(x) over (partition by id) as sum_x
from (
  select ...., 
         ... as x
  from ...
) t
order by id;