想要从Postgresql中不同表的多行中的表中分配金额

时间:2019-02-01 12:01:58

标签: sql postgresql

我有两个如下表

Table 1 :                 Table 2:
id item_id tbl_id amount       id tbl_id amount
1     1     1       50           1    1     60
2     3     1       40           2    2     30
3     2     1       20
4     1     2       50

我想基于公共列tbl_id将tbl2数量即60分配给表1行。查询应该给我结果如下:

tbl1.id tbl1.item_id tbl1.tbl_id tbl1.amount tbl2.amount
   1        1            1          50            50
   2        3            1          40            10
   3        2            1          20             0
   4        1            2          50            30

谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用累计金额:

select t1.*,
       (case when running_amount < t2.amount
             then t1.amount
             when running_amount - t1.amount < t2.amount
             then t2.amount - t1.amount
             else 0
        end) as table2_amount
from (select t1.*,
             sum(t1.amount) over (partition by t1.tbl_id order by t1.id) as running_amount
      from table1 t1
     ) t1 join
     table2 t2
     on t2.id= t1.tbl_id;

答案 1 :(得分:0)

@Gordon Linoff:感谢您的回答作为我提出问题的基础。 下面是获取上述输出的查询。

LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
         mMap.moveCamera(CameraUpdateFactory.newLatLng(myCoordinates));

    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 17.0f));

    marker.setPosition(myCoordinates);