【问题标题】:SQL Server - Select Multiple Rows Data From One Table And Update Multiple Rows Data On Another Table With First Selected DataSQL Server - 从一个表中选择多行数据并使用第一个选择的数据更新另一个表上的多行数据
【发布时间】:2012-01-07 21:53:07
【问题描述】:

我将尽可能简单地解释它。现在我有一个table_1,其中有priceitemId。我还有另一张桌子table_2,里面有totalprice,itemId

我想做的是将table_1中的所有priceitemId分组,并使用itemId键作为公共列更新table_2中的价格总和。

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

这可能吗?谢谢。

SQL Server 2008 R2

【问题讨论】:

    标签: sql sql-server tsql sql-server-2008-r2 sql-update


    【解决方案1】:

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

    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 更新现有行并在缺少时添加新行。

    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/

    【讨论】:

    • 试图让它发挥作用。目前给出错误。 T1 没有 totalprice 列。
    • 现在工作真棒 :) 命名是关键。就像 T1 和 T2 一样
    猜你喜欢
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 2013-07-25
    • 2014-01-01
    • 2012-12-22
    相关资源
    最近更新 更多