将值分配在一列和一组行中,均匀地按比例分配其他行

时间:2014-03-03 21:05:58

标签: sql sql-server

我知道,我困惑了你。

我有这些数据:

对于三个NULL项,我需要:

  1. 添加它们(1828.94 + 772.90 + 0.00)。
  2. 根据每个ItemID的数量,均匀地按比例分配每个ItemID中的总数。
  3. 请注意,ItemIDs相同,但这没关系。

    基本上,最终结果将是相同的列,而没有3行具有ItemID = NULL,并且Amount列将增加一些,因为我正在分配ItemID之间的数量。

    我很难做到这一点而不必做一堆循环。

    任何人都可以帮我一把吗?

2 个答案:

答案 0 :(得分:1)

您可以使用此查询获得分摊金额:

select t.*,
       x.AmountToSplit * t.qty / x.TotalQty as AmountToAdd
from t cross join
     (select sum(case when itemId is null then amount end) as AmountToSplit,
             sum(case when itemId is not null then Qty end) as TotalQty
      from t
     ) x
where t.itemId is not null;

如果您确实想要更新金额,请将其用作可更新的CTE:

with toupdate as (
      select t.*,
             x.AmountToSplit * t.qty / x.TotalQty as AmountToAdd
      from t cross join
           (select sum(case when itemId is null then amount end) as AmountToSplit,
                   sum(case when itemId is not null then Qty end) as TotalQty
            from t
           ) x
      where t.itemId is not null
     )
update toupdate
    set Amount = Amount + AmountToAdd;

答案 1 :(得分:1)

这会对您要做的事情有用吗?

DECLARE @NullAmounts MONEY,
        @RowCount INT

SELECT @NullAmounts = SUM(CASE WHEN ItemID IS NULL THEN Amount ELSE 0 END),
       @RowCount = COUNT(*)
FROM Table

UPDATE Table
SET Amount = Amount + (@NullAmounts / @RowCount)
WHERE
    ItemID IS NOT NULL

当然,在您运行更新后,您可以DELETE这些行,这样您就不会在SELECT语句中返回这些行。

DELETE Table
WHERE ItemID IS NULL