Fetch last record based for reporting

Fetch last record based for reporting

Can this be done?  Please advise...Thank you!

payment table: customer, billing code and payment information

I need to fetch the last payment made into "Payment_Details" by customer AND each billing code for reporting
so basically for each customer I need to get last payment made in each billing code

I have many iterations of the code below and it's not working properly.


    IDList = List();
    IDList.clear();
    for each R in Payment_Details  [Customer_ID ==input.Customer_ID]
    {
        PRec  =  Payment_Details  [(Billing_Code == R.Billing_Code)] sort by Customer_ID  ,Billing_Code  ,Modified_Time desc range from 1 to 1;
        IDList.add(PRec.ID);
  }