如何获取每个员工的最大日期值?

时间:2018-06-20 07:56:54

标签: mysql greatest-n-per-group

对此查询我很累,请帮助我。

select max(cr.`CARD_RECHARGE_ID`),cp.`FULL_NAME` as userName , cr.`CHARGE_DATE` as lastRechargeDate,cr.`CUSTOMER_ID`
from nettxs_communication.customerprofile cp
LEFT JOIN nettxs_communication.cardrecharge cr ON cr.`CUSTOMER_ID` = cp.`CUSTOMER_ID` 
group by cr.`CUSTOMER_ID` ORDER BY cr.`CHARGE_DATE`;

enter image description here

1 个答案:

答案 0 :(得分:0)

据我的理解,您想从cardrecharge中为每个CUSTOMER_ID选择一个与相关的最新条目

select cp.CUSTOMER_ID,
    cp.FULL_NAME,
    cr.CHARGE_DATE as lastRechargeDate,
    cr.CARD_RECHARGE_ID
from customerprofile cp
left join cardrecharge cr ON cr.CUSTOMER_ID = cp.CUSTOMER_ID
join (
    select CUSTOMER_ID, max(CHARGE_DATE) CHARGE_DATE
    from cardrecharge
    group by CUSTOMER_ID
) cr1 on cr.CUSTOMER_ID = cr1.CUSTOMER_ID and cr.CHARGE_DATE = cr1.CHARGE_DATE