使用MYSql从最大表值插入值

时间:2015-01-14 18:07:29

标签: mysql database

我有一个名为CusPayment

的表格
PID     Date        No      TotalPaid
8523    05-Oct-14   GB0213  $300.00
8523    08-Nov-14   GB0213  $500.00
12659   28-Nov-14   N02007  $100.00
12659   07-Dec-14   N02007  $200.00
8523    07-Dec-14   GB0213  $700.00
12659   04-Jan-15   N02007  $300.00
8523    04-Jan-15   GB0213  $900.00

我希望根据max TotalPaid插入CardNo,结果为

PID       Date      CardNo  TotalPaid
8523    07-Dec-14   GB0213  $700.00
12659   04-Jan-15   N02007  $300.00

1 个答案:

答案 0 :(得分:0)

您可以使用insert into select子句

如果同一张卡在不同日期有两个最大值,您将同时选择

insert into Table1 
select c.pid, c.date, c.cardno, c.TotalPaid 
from cusPayment c 
join ( select cardno, max(TotalPaid) as maxPaid 
       from CusPayment group by cardno ) t 
on c.cardno = t.cardno and c.TotalPaid = t.maxPaid