My table:
date Id name amount payment
01/05/2017 01 Maxi 50000 Dec’16
01/10/2017 02 Shirly 50000 Jan’17
01/28/2017 01 Maxi 100000 Jan’17
02/12/2017 02 Shirly 50000 Feb’17
What query do I need to get this in MySQL?
Id name SUM(amount) LAST(payment)
01 Maxi 1,50,000 Jan’17
02 Shirly 100,000 Feb’17
SELECT Id,name,SUM(amount),MAX(STR_TO_DATE(payment,'%b’%y')) AS LAST(payment) FROM TABLENAME GROUP BY Id
Try above code. Hope this will help you.
You can use group_concat
to accumulate the payment values in a certain order, and then use substring_index
to extract the first from that:
select id,
name,
sum(amount),
substring_index(group_concat(payment order by date desc), ',', 1)
from mytable
group by id
This assumes you want to take the last payment in the order by the date column. The payment column seems to be a non-date value, which will be useless to sort by.
If you need to take the last value of payment in the order of payment date, you should define that column as a date. Then you can do a simple max
:
select id,
name,
sum(amount),
max(payment)
from mytable
group by 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.