34,576
社区成员
发帖
与我相关
我的任务
分享
if not object_id(N'Tempdb..#tmp_1') is null
drop table #tmp_1
Go
Create table #tmp_1([NAME] nvarchar(50),[QTY] DECIMAL(18,2))
Insert #tmp_1
select N'a',50 union all
select N'b',100 union all
select N'c',60 union all
select N'd',80
Go
if not object_id(N'Tempdb..#tmp_2') is null
drop table #tmp_2
Go
Create table #tmp_2([ID] int ,[NAME] nvarchar(50),[QTY] DECIMAL(18,2))
Insert #tmp_2
select 1,'a',50 union all
select 2,'a',100 union all
select 3,'b',20 union all
select 4,'b',20 union all
select 5,'b',90 union all
select 6,'c',100 union all
select 7,'d',20 union all
select 8,'d',50
GO
--code
;WITH a AS (
SELECT id,NAME,b.qty ,IIF(total<=0,qty,qty-total) used_qty,total
,ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY id DESC ) AS rno
FROM (
SELECT a.id,a.NAME,a.qty,SUM(a.qty) OVER(PARTITION BY a.NAME ORDER BY a.id) AS total
FROM (
SELECT id,NAME,qty from #tmp_2
UNION
SELECT 0,NAME,qty*(-1) from #tmp_1
) a
) b
WHERE b.qty>b.total
)
SELECT a.id,a.NAME,b.qty AS required_qty,a.qty,a.used_qty,IIF (a.rno=1 ,a.total,0) AS surplus_qty
FROM a
LEFT JOIN #tmp_1 b ON b.NAME=a.NAME
ORDER BY a.id
之前写的一个很类似的例子,LZ可以参考下