简体   繁体   中英

How can I get the Unique ID and MAX(date)?

Could someone help me please. I don't know what wrong with the query I think it's is right..

Item Table 项目

Loan Table
贷款

Pawner Table
当兵

Loan_assignment Table 贷款分配

This is my query for getting the unique ID and MAX(date)

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;

The result of the above^ query is this: 在此处输入图片说明

The result that I like to happen is this below 在此处输入图片说明

Based on comments, if you want the highest date_loan_granted value for each pawner_id, and not each (pawner_id, item_id) you might instead want:

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

Try this:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM