具有按语句分组的SQL更新无效

时间:2015-06-11 15:30:20

标签: sql-server join group-by sum sql-update

我有两个临时表。

在表格@due_cte中,我有一系列Customer_Ids,后跟代码中各个点收集的payment金额。

@work表包含许多不同的列,包括hist_amt_due.

我想要做的是使用@work中的amt_due更新@due_ctegroup/sum更新所有customer_ID

我的原始代码:

update  @work
set     hist_amt_due = sum(isnull(due_amt,0)
from    @work w
join    @due_cte d on w.pmt_customer_no = d.pmt_customer_no
group by  w.pmt_customer_no 

后面是错误消息:

Incorrect syntax near the keyword 'group'.

经过一番挖掘后,我发现我应该使用内连接,所以我尝试了这个,但这也是不行的。

update  @work
set     hist_amt_due = isnull(d.due_amt,0)
from    @work w
inner join  (SELECT pmt_customer_no, sum(isnull(due_amt,0)) from @due_cte group by pmt_customer_no) AS d on w.pmt_customer_no = d.pmt_customer_no

错误讯息:

No column name was specified for column 2 of 'd'. 

Invalid column due_amount

我对如何危害这一点感到茫然。

示例数据:

pmt_customer_no  |  due_amt
1                   50
2                   30
3                   0
4                   30
2                   10
1                   20
5                   80

@work应该更新 - 客户编号 1 due_amout应该是: 70 ,其中 > 2 然后due_amount 40 ,等等。

1 个答案:

答案 0 :(得分:0)

试试这个:

update w set hist_amt_due = d.s
from @work w
join (select pmt_customer_no, sum(isnull(due_amt, 0)) s 
      from @due_cte group by pmt_customer_no)d on w.pmt_customer_no = d.pmt_customer_no