根据其他联接表列计算字段的总和

时间:2019-03-31 16:21:35

标签: sql postgresql join left-join right-join

我正在处理这样的SQL查询:

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;

上面的输出将是这样的:

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

我需要在结果中添加一个新列,该列基于amount_paid的值对field4进行求和(如果它们相同)。

上面的查询返回如下:

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

但是预期结果如下:

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

任何建议都对您有帮助。

1 个答案:

答案 0 :(得分:1)

您似乎只想要

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