需要帮助在sql中选择distinct和max字段

时间:2017-01-24 16:12:23

标签: sql postgresql

所以在nc_sno.netcredit_dist_lp1表中,有贷款号码和身份证号码。每个贷款号码最多可以有两个不同的ID号。我想为每个贷款号码提取最高的身份证号码。这就是我所拥有的。谢谢你的帮助:

select
  tempkk3.loan_number
,tempkk3.username
, tempkk3.week_number
,lp.lp_rules_instruction as lp_instruction
,lp.insert_timestamp as time_entered_queue
,lp.id
from
  nc_sno.netcredit_dist_lp1 lp
join tempkk3 using (loan_number)

1 个答案:

答案 0 :(得分:1)

Postgres具有非常好的distinct on功能,它可以完全满足您的需求:

select distinct on (loan_number) loan_number,
       tempkk3.username, tempkk3.week_number,
       lp.lp_rules_instruction as lp_instruction,
       lp.insert_timestamp as time_entered_queue,
       lp.id
from nc_sno.netcredit_dist_lp1 lp join
     tempkk3
     using (loan_number)
order by loan_number, id desc;