简体   繁体   中英

SUM a calculated value based on ID

So i have something like this:

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

I'm trying to get the X summed based on WB.ID

DURA and DISTA are both joined and are not db tables(local). same goes to t and 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

RESULT:

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

From the sample data, this looks like a simple sum using a window function:

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

If x is the result of another query, use a derived table:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM