SQL Server - 从一个表中选择多行数据并使用第一个选定的数据更新另一个表上的多行数据

发布于 2024-12-18 04:18:38 字数 473 浏览 2 评论 0原文

我将尽可能简单地解释它。现在我有一个 table_1,其中包含 priceitemId。我还有另一个表 table_2,其中包含 totalprice,itemId

我想要做的是将 table_1 中按 itemId 分组的所有 price 相加,并更新 table_2 中的价格总和> 以 itemId 键作为公共列。

table_1 中汇总的每个 itemId 的价格应更新 table_2 中的 totalprice 列。

这可能吗?谢谢。

SQL Server 2008 R2

I am going to explain it as simple as possible. Now I have a table_1 which has price and itemId. I also have another table table_2 which has totalprice,itemId.

What I want to do is to sum all price from table_1 grouped by itemId and update that sum of price in table_2 with itemId key as the common column.

The price per itemId summed from table_1 should update the totalprice column in table_2.

Is that possible ? Thank you.

SQL Server 2008 R2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

豆芽 2024-12-25 04:18:38

是的,有可能吗?您可以这样做:

update T2
set totalprice = T1.totalprice
from Table_2 as T2
  inner join (select sum(price) as totalprice,
                     itemid
              from Table_1
              group by itemid) as T1
    on T2.itemid = T1.itemid

https://data.stackexchange.com/stackoverflow/q/119388 /

如果您还没有 table_2 中的所有 itemid,您可以使用 合并 以更新现有行并添加新行(如果缺少)。

merge Table_2 as T2
using (select sum(price) as totalprice,
              itemid
       from Table_1
       group by itemid) as T1
on T1.itemid = T2.itemid
when matched then 
  update set totalprice = T1.totalprice
when not matched then 
  insert (totalprice, itemid) 
  values(T1.totalprice, T1.itemid);

https://data.stackexchange.com/stackoverflow/q/119389/

Yes is it possible. You can do like this:

update T2
set totalprice = T1.totalprice
from Table_2 as T2
  inner join (select sum(price) as totalprice,
                     itemid
              from Table_1
              group by itemid) as T1
    on T2.itemid = T1.itemid

https://data.stackexchange.com/stackoverflow/q/119388/

If you don't already have all itemid's in table_2 you can use a merge to update the existing rows and add a new row if it is missing.

merge Table_2 as T2
using (select sum(price) as totalprice,
              itemid
       from Table_1
       group by itemid) as T1
on T1.itemid = T2.itemid
when matched then 
  update set totalprice = T1.totalprice
when not matched then 
  insert (totalprice, itemid) 
  values(T1.totalprice, T1.itemid);

https://data.stackexchange.com/stackoverflow/q/119389/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文