Postgresql:如何从多个值的映射中 select
Postgresql: how to select from map of multiple values
我有一个 SOME_DELTA table 记录所有与金额变化相关的交易方
例如:
PARTY_ID | SOME_DATE | AMOUNT
--------------------------------
party_id_1 | 2019-01-01 | 100
party_id_1 | 2019-01-15 | 30
party_id_1 | 2019-01-15 | -60
party_id_1 | 2019-01-21 | 80
party_id_2 | 2019-01-02 | 50
party_id_2 | 2019-02-01 | 100
我有一个 MVC 控制器接受映射 someMap(party_id, some_date) 的情况,我需要得到 part_id 列表,其中包含总金额直到特定 some_date
在这种情况下,如果我将 mapOf("party_id_1" 发送到 Date(2019 - 1 - 15),"party_id_2" 到 Date(2019 - 1 - 2))
我应该得到 party_id 的列表,总金额直到 some_date
输出应如下所示:
party_id_1 | 70
party_id_2 | 50
目前代码是:
select sum(amount) from SOME_DELTA where party_id=:partyId and some_date <= :someDate
但在这种情况下,我需要遍历地图并进行多次数据库调用以获得 eatch party_id 的总金额,直到 some_date 感觉不对
是否有更巧妙的方法来进入一个 select 查询? (避免 +100 次数据库调用)
您可以为此使用横向连接:
select map.party_id,
c.amount
from (
values
('party_id_1', date '2019-01-15'),
('party_id_2', date '2019-01-02')
) map (party_id, cutoff_date)
join lateral (
select sum(amount) amount
from some_delta sd
where sd.party_id = map.party_id
and sd.some_date <= map.cutoff_date
) c on true
order by map.party_id;
我有一个 SOME_DELTA table 记录所有与金额变化相关的交易方 例如:
PARTY_ID | SOME_DATE | AMOUNT
--------------------------------
party_id_1 | 2019-01-01 | 100
party_id_1 | 2019-01-15 | 30
party_id_1 | 2019-01-15 | -60
party_id_1 | 2019-01-21 | 80
party_id_2 | 2019-01-02 | 50
party_id_2 | 2019-02-01 | 100
我有一个 MVC 控制器接受映射 someMap(party_id, some_date) 的情况,我需要得到 part_id 列表,其中包含总金额直到特定 some_date
在这种情况下,如果我将 mapOf("party_id_1" 发送到 Date(2019 - 1 - 15),"party_id_2" 到 Date(2019 - 1 - 2)) 我应该得到 party_id 的列表,总金额直到 some_date
输出应如下所示:
party_id_1 | 70
party_id_2 | 50
目前代码是:
select sum(amount) from SOME_DELTA where party_id=:partyId and some_date <= :someDate
但在这种情况下,我需要遍历地图并进行多次数据库调用以获得 eatch party_id 的总金额,直到 some_date 感觉不对
是否有更巧妙的方法来进入一个 select 查询? (避免 +100 次数据库调用)
您可以为此使用横向连接:
select map.party_id,
c.amount
from (
values
('party_id_1', date '2019-01-15'),
('party_id_2', date '2019-01-02')
) map (party_id, cutoff_date)
join lateral (
select sum(amount) amount
from some_delta sd
where sd.party_id = map.party_id
and sd.some_date <= map.cutoff_date
) c on true
order by map.party_id;