我有两张桌子:" debt_period"和"付款"。我需要从他们那里看一看。有一种情况可以在一个时期内支付一些款项。因此,在这种情况下,我必须将付款值汇总到一列,并列出另一列中逗号分隔的日期。 我使用string_agg(to_char(p.payment_date,' DD.MM.YYYY')和窗口函数。 这很好用。问题是字符串中的日期不是按时间顺序排列的。我怎么订购它们?
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
答案 0 :(得分:0)
尝试使用这个:
更改
LEFT JOIN base.payments p on (p.period_id = dp.id)
通过
LEFT JOIN (select * from base.payments order by period_id,payment_date) p on (p.period_id = dp.id)
最终结果
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 (select * from base.payments order by period_id,payment_date) p on (p.period_id = dp.id)
WHERE dp.card_id = '№001137'
ORDER BY dp.card_id
答案 1 :(得分:0)
我一直在寻找这种功能,@ Mesbah回答的还有另一种方法
请参阅此处: https://www.postgresql.org/docs/9.0/sql-expressions.html 4.2.8。窗口函数调用
基本上,您可以定义o OR BY BY,OVER BY
以及指定要在窗口中包括哪些行(在下面的示例中,该窗口覆盖所有行)
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
ORDER BY payment_date
range between unbounded preceding and unbounded following -- used to aggregate full range
) 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