如何从表中选择最大当前值

时间:2017-01-07 12:31:12

标签: mysql sql

    SELECT
    credit_detail.bill_id,
    credit_detail.credit_id
    FROM credit_detail
   WHERE credit_detail.credit_id=(SELECT max(credit_id)FROM credit_detail )

输入:

bill_id credit_id
 2 4 
 6 8 
 2 17 
 6 12

预期

Bill_id credit_id 
 2 17 
 6 12

1 个答案:

答案 0 :(得分:1)

您可以在bill_id上执行group by以获得最大的credit_id,如下所示:

select 
  bill_id,
  max(credit_id) credit_id
from credit_details
group by bill_id

如果credit_details中有更多列要获取max credit_id,请使用:

select c1.*
credit_details c1 inner join (
    select bill_id, max(credit_id) credit_id
    from credit_details
    group by bill_id
) c2 on c1.bill_id = c2.bill_id
    and c1.credit_id = c2.credit_id;