使用其值与另一个值的总和更新记录

时间:2015-06-26 15:01:23

标签: sql-server

我想使用自身和另一行的值更新记录的值,而不使用查询的set部分中的一堆选择来组合2.假设您已经知道两行的主键。 / p>

以下是前后应该发生的事情的一个例子:

在:

| pk_id|allocated|purchased|installed|
|    10|        2|        5|       10|
|     3|        8|        6|        2|
|    11|        2|        6|        7|

后:

| pk_id|allocated|purchased|installed|
|    10|        2|        5|       10|
|     3|        8|        6|        2|
|    11|        4|       11|       17|

我不想做这样的事情:

UPDATE Example
set allocated = (select allocated from Example where pk_id = 10) 
                + (select allocated from Example where pk_id = 11),
    purchased = (select purchased from Example where pk_id = 10) 
               + (select purchased from Example where pk_id = 11),
    installed = (select installed from Example where pk_id = 10) 
               + (select installed from Example where pk_id = 11)
    WHERE pk_row = 11

所有这些选择似乎真的没必要,但我想不出更好的方法。

4 个答案:

答案 0 :(得分:1)

如果你知道记录键:

DECLARE @Id1 INT = 10, @Id2 INT = 11

;WITH CTE AS
(
  SELECT @Id2 Id, SUM(allocated) Allocated, SUM(purchased) Purchased, 
         SUM(installed) Installed
  FROM YourTable
  WHERE pk_id IN (@Id1 ,@Id2)
)
UPDATE t SET allocated = c.Allocated, purchased = c.Purchased, 
             installed = c.Installed
FROM YourTable t
         JOIN CTE c ON t.pk_id = c.id

答案 1 :(得分:0)

这当然不是最有效的方法。这是将查询减少一半的另一种方法。丑陋的部分是您存储每行中组的聚合数据。这是一个维持而不是正常化的噩梦。

UPDATE Example
set allocated = (select sum(allocated) from Example where pk_id in (10, 11)),
    purchased = (select sum(purchased) from Example where pk_id in (10, 11)),
    installed = (select sum(installed) from Example where pk_id in (10, 11))
WHERE pk_row = 11

答案 2 :(得分:0)

您可以通过将行连接到要添加的行来更新该行。像这样:

UPDATE Example
SET allocated = Example.allocated + OtherRow.allocated,
    purchased = Example.purchased + OtherRow.purchased,
    installed = Example.installed + OtherRow.installed 
FROM Example
INNER JOIN Example AS OtherRow ON OtherRow.pk_row = 10
WHERE Example.pk_row = 11

答案 3 :(得分:0)

这样,您可以在加入之前使用SUM。我相信只有当你将多行汇总到另一行时才能在加入之前进行求和。否则,我没有看到使用这种方法的意义。特别是因为它查询了同一行的两次而不是一次。

DECLARE @Pk10 INT = 10, 
        @Pk11 INT = 11

UPDATE Example
SET allocated = OthersRows.allocatedTotal,
    purchased = OthersRows.purchasedTotal,
    installed = OthersRows.installedTotal 
FROM Example
INNER JOIN (SELECT  PkToUpdate = @Pk11,
                    allocatedTotal = SUM(allocated),
                    purchasedTotal = SUM(purchased),
                    installedTotal = SUM(installed)
            FROM Example
            WHERE Example.pk_row IN (@Pk10, @Pk11)) AS OthersRows ON Example.pk_row = OthersRows.PkToUpdate