【发布时间】:2017-05-12 20:35:59
【问题描述】:
我需要有关如何将行值分配给具有相同 ID 的多行的 SQL Server 帮助。为了说明,
- Id = ProductInventoryCode
- 数量 = 数量库存
为了分发:
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 个单位要少。
【问题讨论】:
标签: sql sql-server sql-server-2008 common-table-expression