account_id?
create view account_balance as
SELECT a.id AS account_id,
currency.id AS currency_id,
COALESCE(SUM(ae.amount), 0) AS amount
FROM account a
CROSS JOIN currency
LEFT JOIN accounting_entry ae ON currency.id = ae.currency_id AND a.id = ae.account_id
GROUP BY 1, 2;
Или
create view account_balance as
SELECT a.id AS account_id,
currency.id AS currency_id,
COALESCE(balance.balance, 0) AS amount
FROM account a
CROSS JOIN currency
LEFT JOIN LATERAL ( SELECT sum(ae.amount) AS balance
FROM accounting_entry ae
WHERE ae.account_id = a.id
AND ae.currency_id = currency.id
GROUP BY ae.account_id, ae.currency_id) balance ON true;
скорее всего 1вый. но лучше замерить во 2ой по lateral как понимаю будет cross apply на каждую строчку перемноженных account+currency
А Вы планы таких запросов смотрели?
И зачем у Вас GROUP BY в подзапросе balance, кстати (во втором варианте, в LATERAL)?
Обсуждают сегодня