SQL Group by Statement 更新无效
SQL Update with a Group by Statement not working
我有两个温度计 table。
在 table @due_cte
中,我有一系列 Customer_Ids
,然后是 payment
在代码的各个点收集的金额。
@work
table 有很多不同的栏目包括 hist_amt_due.
我想做的是用 @due_cte
中的 amt_due 更新 @work
,但 group/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,等等
试试这个:
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
我有两个温度计 table。
在 table @due_cte
中,我有一系列 Customer_Ids
,然后是 payment
在代码的各个点收集的金额。
@work
table 有很多不同的栏目包括 hist_amt_due.
我想做的是用 @due_cte
中的 amt_due 更新 @work
,但 group/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,等等
试试这个:
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