左连接表SQL的UPDATE SUM

时间:2018-01-11 07:01:07

标签: sql

TBLOAN

accountno(varchar(16) | payno(int) | payamount(decimal,16,2) | 
----------------------------------------------------------------------------
001                   | 3          | 300                     
002                   | 3          | 300

TBPAY

accountno(varchar(16) | ilno(int) | amount(decimal,16,2) | paydt (datetime)
-------------------------------------------------------------------------
001                   | 1          | 100                 | 11-15-2017 
001                   | 2          | 100                 | 11-30-2017
001                   | 3          | 100                 | 12-15-2017
002                   | 1          | 100                 | 11-30-2017
002                   | 2          | 100                 | 12-15-2017
002                   | 3          | 100                 | 12-30-2017

我的SELECT查询是:

SELECT MAX(p.ilno),SUM(p.amount),l.accountno,l.payno,l.payamount 
FROM TBLOAN l 
  LEFT JOIN TBPAY p on l.accountno = p.accountno 
where p.paydt <= '11-30-2017' group by l.accountno,l.payno,l.payamount

结果:

p.ilno | p.amount | accountno | payno | payamount
----------------------------------------------------------------------------
2      | 200      | 001       | 2     | 200                             
2      | 200      | 002       | 1     | 100   

如何像这样更新TBLOAN:

UPDATE l SET l.payno = MAX(p.ilno), l.payamount = p.SUM(p.amount) 
FROM TBLOAN l 
  LEFT JOIN TBPAY p on l.accountno = p.accountno 
where p.paydt <= '11-30-2017'

它说我不能在UPDATE语句中使用聚合。

1 个答案:

答案 0 :(得分:1)

UPDATE l SET l.payno = sub.m1, l.payamount = sub.s1 
FROM TBLOAN l 
  JOIN (SELECT MAX(p.ilno) as m1,SUM(p.amount) as s1,l.id 
        FROM TBLOAN l 
            LEFT JOIN TBPAY p on l.accountno = p.accountno 
        where p.paydt <= '11-30-2017'
        GROUP BY l.id) sub ON sub.id=l.id

您可以将此作为子查询添加,并按ID进行分组,然后加入TBLOAN