27,581
社区成员




DECLARE @TABLE TABLE
(
客户 varchar(10),
医院 NVARCHAR(10),
合同金额 INT,
销售总额 INT
)
insert into @TABLE values
('A','H1',100,300),
('A','H2',120,300),
('B','H3',80,60),
('C','H4',90,120),
('C','H5',100,120),
('C','H6',50,120);
WITH CTE AS
(
SELECT *,ROW_NUMBER()over(order by 客户) id
FROM @TABLE A
)
,cte1 as
(
select a.*,sumqty=(select SUM(合同金额) from CTE where 客户 = a.客户 and id <= a.id),
jcqty = 销售总额 - (select SUM(合同金额) from CTE where 客户 = a.客户 and id <= a.id)
from CTE a
)
,cte2 as
(
select
id,客户,医院,合同金额,sumqty,jcqty,销售总额,
完成情况 =
case when jcqty >= 0 then 合同金额
when jcqty <0 and ABS(jcqty)<=合同金额 then 合同金额 + jcqty
when jcqty < 0 and ABS(jcqty)>合同金额 then 0
end
from cte1
),cte3 as
(
select *,ROW_NUMBER()over(partition by 客户 order by getdate()) nid from cte2
)
select * into #test from cte3
update a set a.完成情况 = a.完成情况 + jcqty from #test a
where jcqty >= 0 and nid =
(select MAX(nid) from #test where 客户 = A.客户)
select * from #test