使用Distinct SUM更新

时间:2012-05-30 02:05:38

标签: sql group-by sum distinct

我找到了一些很好的资源,表明我应该能够将选择查询与更新合并,但我无法理解正确的格式。

我有一个select语句,它正在为我获取信息,我想几乎使用这些结果来更新与select查询中的accountID匹配的帐户表。

这是select语句:

SELECT DISTINCT SUM(b.workers)*tt.mealTax as MealCost,b.townID,b.accountID
FROM buildings AS b
INNER JOIN town_tax AS tt ON tt.townID = b.townID
GROUP BY b.townID,b.accountID

因此,简而言之,我希望将上述查询与以下内容合并:

UPDATE accounts AS a
SET a.wealth = a.wealth - MealCost

其中MealCost是select查询的结果。我确信有一种方法可以将它合二为一,我只是无法连接点以使其一致运行而不会分成两个查询。

1 个答案:

答案 0 :(得分:1)

首先,当你有一个小组时,你不需要那个。

其次,您打算如何将这两个结果联系起来? SELECT查询每个帐户返回多行(每个城镇一个)。据推测,帐户表只有一行。假设您想要更新的平均MealCost。

获取此选项的选择查询是:

SELECT accountID, avg(MealCost) as avg_Mealcost
FROM (SELECT SUM(b.workers)*tt.mealTax as MealCost, b.townID, b.accountID
      FROM buildings AS b INNER JOIN
           town_tax AS tt
           ON tt.townID = b.townID
      GROUP BY b.townID,b.accountID
     ) a
GROUP BY accountID

现在,要将其置于更新中,您可以使用如下语法:

UPDATE accounts
    set accounts.wealth = accounts.wealth + asum.avg_mealcost
    from (SELECT accountID, avg(MealCost) as avg_Mealcost
          FROM (SELECT SUM(b.workers)*tt.mealTax as MealCost, b.townID, b.accountID
                FROM buildings AS b INNER JOIN
                     town_tax AS tt
                     ON tt.townID = b.townID
                GROUP BY b.townID,b.accountID
               ) a
          GROUP BY accountID
         ) asum
    where accounts.accountid = asum.accountid

这使用SQL Server语法,我认为这与Oracle和大多数其他数据库相同。 Mysql在“set”之前放置“from”子句,并在“update accounts”上允许别名。