我有两张桌子:
Customers
(custid,tot_sales,tot_profits)
Invoices
(custid,销售,利润)
发票可以为同一客户提供一到多张发票。
我试图计算发票的总销售额和利润,并将其保存在客户手中。
我就在这里:
select custid, sum(revenus), sum(profits)
from invoices
group by cust
它让我回来了:
CustId Revenus Profits
1 1000 200
2 2000 300
到目前为止一切顺利。
我现在不知道如何在同一声明中将数据推送回客户。我在想
udpate customers
set tot_revenus, tot_profits
select custid, sum(revenus), sum(profits)
from invoices
group by cust
但它没有用。
非常感谢任何帮助
由于
答案 0 :(得分:1)
您应该使用update with join
:
UPDATE Customers c
INNER JOIN (SELECT custId,sum(revenus) as sum_rev,sum(profits) as sum_prof
FROM Invoices
GROUP BY custId) i
ON(c.custId = i.custId)
SET c.tot_sales = i.sum_rev,
c.tot_profits = i.sum_prof
这将基本上根据创建的customers
表更新derived
表(包含每个客户的总和)。