如何获得唯一ID和MAX(日期)?

时间:2015-07-12 14:13:20

标签: mysql sql database-administration

是的,请有人帮助我。我不知道查询有什么问题我觉得它是对的..

项目表 item

贷款表
loan

Pawner表
pawner

Loan_assignment表 loan_assignment

这是我获取唯一ID和MAX(日期)的查询

SELECT distinct p.pawner_id, c.item_name, c.description, l.net_proceeds, 
max(DATE_FORMAT(a.date_loan_granted, '%d-%b-%Y')) as date 
from pawner p, loan l, collateral c, loan_assignment a, pawnshop b 
WHERE b.pawnshop_id = a.pawnshop_id AND p.pawner_id = a.pawner_id 
AND l.loan_id = a.loan_id AND a.item_id = c.item_id 
AND b.pawnshop_id = 1 group by p.pawner_id;

以上^查询的结果如下: enter image description here

我喜欢的结果如下 enter image description here

2 个答案:

答案 0 :(得分:2)

根据评论,如果你想要每个pawner_id的最高date_loan_granted值,而不是每个(pawner_id,item_id),你可能想要:

select m.pawner_id,
       i.item_name,
       i.description,
       l.net_amount,
       date_format(m.date_loan_granted, '%d-%b-%Y') as date_loan_granted
  from (select pawner_id,
               max(loan_id) as loan_id,
               max(date_loan_granted) as date_loan_granted
          from loan_assignment
         group by pawner_id) m
  join loan_assignment la
    on m.pawner_id = la.pawner_id
   and m.loan_id = la.loan_id
   and m.date_loan_granted = l.date_loan_granted
  join loan l
    on m.loan_id = l.loan_id
  join item i
    on la.item_id = i.item_id

答案 1 :(得分:1)

试试这个:

SELECT distinct p.pawner_id, c.item_name, c.description, l.net_proceeds, 
DATE_FORMAT(MAX(a.date_loan_granted), '%d-%b-%Y') as date 
from pawner p, loan l, collateral c, loan_assignment a, pawnshop b 
WHERE b.pawnshop_id = a.pawnshop_id AND p.pawner_id = a.pawner_id 
AND l.loan_id = a.loan_id AND a.item_id = c.item_id 
AND b.pawnshop_id = 1 group by p.pawner_id;