如何在此select语句中分组?

7y4bm7vi  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(311)
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

如何按合同id分组?我使用的是postgresql9.6新编辑:所以我的目标是得到一个合同的总天数。然后还要显示该特定数据点的其余信息,因此我还要选择表中的其余列。那些专栏我不想做任何事。让他们保持原样。

tkclm6bt

tkclm6bt1#

如果你想要一排 contract_id 那你可以用 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;

这将返回包含最新值的行 duedate 对于每个合同(满足 where 当然是条件)。

mzaanser

mzaanser2#

根据我对你的问题的理解,你只需要按一列进行分组。我认为这可以在postgresql中完成。有关更多选项,请参阅https://www.postgresqltutorial.com/postgresql-group-by/#:~:text=introduction%20to%20postgresql%20group%20by%20clause&text=select%20column\u 1%2c%20column\u 2%2c%20aggregate\u函数(,列出%20of%20comma%2dseparated%20columns)。

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
GROUP BY customer_id
order by duedate asc

相关问题