select '2020-07-02'::date - "duedate"::date as days_passed_since_invoice_was_sent, duedate, contract_id, paiddate, paymentdueon, component, record_valid_from, dueamount, unpaidamount, waivedamount from dwd_tb_payment_schedule where record_valid_to = '9999-12-31' and unpaidamount > 0 order by duedate asc
how do I group by contract_id? I’m using postgresql 9.6 new edit: So my aim here is to get the total nr of late days a contract_id has. and then also to show the rest of the information for that specific data point, hence I’m also selecting the rest of the columns in my table. Those columns I don’t wish anything to be done with. Just leave them as they are.
Advertisement
Answer
If you want one row per contract_id
then you can use distinct on
:
select distinct on (contract_id) ('2020-07-02'::date - "duedate"::date) as days_passed_since_invoice_was_sent, duedate, contract_id, paiddate, paymentdueon, component, record_valid_from, dueamount, unpaidamount, waivedamount from dwd_tb_payment_schedule where record_valid_to = '9999-12-31' and unpaidamount > 0 order by contract_id, duedate asc;
This returns the row with the latest duedate
for each contract (that meets the where
conditions of course).