I have two tables: "debt_period" and "payments". I need to take a view of them. There is a situation when can be a few payments for one period. So in such case, I have to sum the payment values in one column and list the dates separated by a comma in the other column. I use string_agg(to_char(p.payment_date, 'DD.MM.YYYY') and window function. This works fine. The problem is that dates in the string are not in chronological order. How can I order them?
CREATE MATERIALIZED VIEW base.v_period_payments AS
SELECT DISTINCT
dp.card_id,
dp.year,
dp.month,
dp.debt_amount,
string_agg(to_char(p.payment_date, 'DD.MM.YYYY'), ', ') OVER ( PARTITION BY p.period_id) AS
pay_dates
FROM base.debt_period dp
LEFT JOIN base.payments p on (p.period_id = dp.id)
WHERE dp.card_id = '№001137'
ORDER BY dp.card_id