22,210
社区成员
发帖
与我相关
我的任务
分享
create table #t(salordcode varchar(10), cgcode varchar(10),sqtp int,purchasecode varchar(10),fqtp int,tobeqtp int,aqtp int,bqtp int,stock int,planqtp int,)
insert into #t(salordcode,cgcode,sqtp,purchasecode,fqtp,tobeqtp,aqtp,bqtp,stock,planqtp)
select '10001','503200',500,'110249',99,401,1500,0,1500,1 union all
select '10002','503200',500,'110249',0,500,1500,0,1500,1 union all
select '10003','503200',600,'110249',0,600,1500,0,1500,1
SELECT
*,CASE WHEN sumtobeqtp<stock THEN 0 ELSE 1 END AS planqtp2
FROM
(
SELECT
*,(SELECT SUM(tobeqtp) FROM #t WHERE cgcode=t1.cgcode AND salordcode<=t1.salordcode) AS sumtobeqtp
FROM #t AS t1
) AS t
SELECT
*,CASE WHEN sumtobeqtp<stock THEN 0 ELSE 1 END AS planqtp2
FROM
(
SELECT
*,SUM(tobeqtp)OVER(PARTITION BY cgcode ORDER BY salordcode) AS sumtobeqtp
FROM #t
) AS t
/*
salordcode cgcode sqtp purchasecode fqtp tobeqtp aqtp bqtp stock planqtp sumtobeqtp planqtp2
10001 503200 500 110249 99 401 1500 0 1500 1 401 0
10002 503200 500 110249 0 500 1500 0 1500 1 901 0
10003 503200 600 110249 0 600 1500 0 1500 1 1501 1
*/
select *,
case when subtotal<=stock then 0 else 1 end as planqtp_new
from #t A
outer apply (select SUM(tobeqtp) as subtotal from #t where cgcode=A.cgcode and salordcode<=A.salordcode) as B