原贴:
https://bbs.csdn.net/topics/619167074
https://learn.microsoft.com/zh-cn/sql/t-sql/functions/lag-transact-sql?view=sql-server-ver16
CREATE TABLE #kcb(
xlh INT,
shul INT,
ftshl INT
)
INSERT INTO #kcb(xlh,shul,ftshl)
SELECT 1,20,0
union
SELECT 2,55,0
union
SELECT 3,100,0
-- 以上为创建测试表及测试数据
--给定30为初值,如何分给1、2、3这三行,分完为止
DECLARE @v INT = 30;
WITH cte AS (
SELECT *,
--以xlh字段排序,累加 shul 值
SUM(shul) OVER(ORDER BY xlh) AS 累加值
FROM #kcb
),cte2 AS(
SELECT *,
--以xlh字段排序,取上1行的累加值,如果没有就取0
lag(累加值, 1, 0) OVER(ORDER BY xlh) AS 上一行累加值
FROM cte
)
SELECT xlh,shul,累加值,上一行累加值,
CASE
WHEN 累加值 <=@v THEN shul
WHEN 累加值 >@v AND 上一行累加值 <@v THEN @v -上一行累加值
ELSE 0
END AS 当前行分配值
FROM cte2