我知道,我困惑了你。
我有这些数据:
对于三个NULL项,我需要:
请注意,ItemIDs相同,但这没关系。
基本上,最终结果将是相同的列,而没有3行具有ItemID = NULL,并且Amount列将增加一些,因为我正在分配ItemID之间的数量。
我很难做到这一点而不必做一堆循环。
任何人都可以帮我一把吗?
答案 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