Calculating the sum of a field based on other join table columns

回眸只為那壹抹淺笑 提交于 2019-12-11 17:12:47

问题


I am working on a SQL query like this:

Select 
    a.field1,
    b.field2,
    c.field3,
    c.field4,
    b.filed5,
    a.field6,
    COALESCE(SUM(d.paid_amt) OVER (PARTITION BY a.some_column), 0)  as amount_paid 
from 
    a 
inner join 
    b on a.field1 = b.field1 
right join 
    c on b.field2 = c.field3 
left join 
    d on d.filed3 = a.field1 and d.field8 = a.field3
where 
    some conditions;

The output of the above would be something like this:

field1 | field2 | field3 | field4 | field5 | field6 | amount_paid
-------+--------+--------+--------+--------+--------+-------------
name   | value1 | other1 | 1      | diff   |   new  | 100
name1  | value2 | other2 | 1      | diff1  |   new1 | 100
name2  | value3 | other3 | 2      | diff2  |   new2 | 100

I need a new column in the result which sums the amount_paid based on field4 value(if they are same).

The above query is returning like below:

field1 | field2 | field3 | field4 | field5 | field6 | amount_paid
-------+--------+--------+--------+--------+--------+-------------
name   | value1 | other1 | 1      | diff   |   new  | 200
some   | value3 | other3 | 2      | diff2  |   new2 | 200

But the expected result is like below:

field1 | field2 | field3 | field4 | field5 | field6 | amount_paid
-------+--------+--------+--------+--------+--------+-------------
name   | value1 | other1 | 1      | diff   |   new  | 200
some   | value3 | other3 | 2      | diff2  |   new2 | 100

Any suggestions are helpful here please.


回答1:


You seem to just want:

Select . . .
       COALESCE(SUM(d.paid_amt) OVER (PARTITION BY c.field04), 0)  as amount_paid 


来源:https://stackoverflow.com/questions/55442937/calculating-the-sum-of-a-field-based-on-other-join-table-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!