简体   繁体   English

在MySQL查询中选择最后一行和列的总和

[英]Select last row and sum of column in MySQL query

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? 我需要什么查询才能在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: 您可以使用group_concat以一定顺序累积付款值,然后使用substring_index从中提取第一个:

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 : 然后,您可以做一个简单的max

select   id, 
         name, 
         sum(amount), 
         max(payment)
from     mytable
group by id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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