Home > Software engineering >  Get sum and order by the last date added
Get sum and order by the last date added

Time:12-14

Using the below query to calculate the total balance:

SELECT ROUND(SUM(credit_in)-SUM(credit_out), 2) as balance,
cw.date_added as last_updated_date
FROM customer_wallet cw
LEFT JOIN customers c ON c.id = cw.cus_id
GROUP BY cw.cus_id
ORDER BY cw.date_added DESC

Also, using order by date_added to get the last added date. But, getting the first date record for each customer. How can I get the last date?

This is SQLFiddle: http://sqlfiddle.com/#!9/585fd2/1

From SQLFiddle, if you will run the query, you will get 2022-12-01T00:00:00Z as last updated date. But, I want, 2022-12-04T00:00:00Z

Please let me know if you need more clarification.

CodePudding user response:

You need to use max function

SELECT ROUND(SUM(credit_in)-SUM(credit_out), 2) as balance, max(cw.date_added) as last_updated_date
FROM customer_wallet cw
LEFT JOIN customers c ON c.id = cw.cus_id
GROUP BY cw.cus_id
ORDER BY cw.date_added DESC

http://sqlfiddle.com/#!9/585fd2/2

  • Related