我需要关于如何将一行值分配给具有相同id的几行的SQL Server帮助。为了说明,
Id = ProductInventoryCode Qty = QuantityInStock
对于Distribution:
一个将接收分布式值的表格。
尽可能地,每个 ID 和分支的分布应该近似相等。
我得到了类似下面的东西,但有点困惑,迷失了方向。
Id = ProductInventoryCode Qty = QuantityInStock
对于Distribution:
Id | Qty | TotalNoOfBranchesWithId
---+--------+-------------------------
1 | 40 | 2
2 | 33 | 3
3 | 21 | 2
一个将接收分布式值的表格。
Id | BranchCode | Qty | QtyFromForDistributionTable
-------------------------------------------------------
1 101 13 20
1 102 8 20
2 101 10 11
2 102 2 10
2 103 3 12
3 101 1 11
3 102 12 10
尽可能地,每个 ID 和分支的分布应该近似相等。
我得到了类似下面的东西,但有点困惑,迷失了方向。
with rs as
(
select
r.*, cume.cumequantity,
coalesce(s.shipped, 0) AS shipped
from
tmpForDistribution r
cross apply
(SELECT SUM([QuantityInStock]) AS cumequantity
FROM tmpForDistribution r2
WHERE r2.ProductInventoryCode = r.ProductInventoryCode) cume
left join
(SELECT ProductInventoryCode, COUNT(ProductInventoryCode) AS shipped
FROM tmpDistributed s
GROUP BY s.ProductInventoryCode) s ON r.ProductInventoryCode = s.ProductInventoryCode
)
select
rs.ProductInventoryCode, rs.cumequantity, rs.QuantityInStock,
***"how to distribute"***
from rs
我目前正在使用SQL Server 2008
这是一个样例屏幕输出
上面的结果是145个分支机构,下面我们使用用于分配数量字段的ForDistributionQty,该字段为3130,我最终得到了一个小数(DistVal = 21.586),这对于此问题来说不正确,它应该是一个整数,例如21,但是,如果只有21,则21 x 145仅为3045,少了85个单位。