--1. 将结果插入临时表
SELECT
*
INTO xxx
FROM(
SELECT TOP 1 a.FQTY,a.fseq
FROM T_SAL_ORDERENTRY as a
WHERE FQTY=5
UNION ALL
SELECT TOP 1 b.FQTY,b.fseq
FROM T_SAL_ORDERENTRY as b
WHERE FQTY=1
) as c
SELECT * FROM xxx
--最初update
-- UPDATE xxx
-- SET FQTY = ISNULL((
-- SELECT TOP 1 a.FQTY
-- FROM xxx AS a
-- WHERE t.fseq >= fseq
-- AND FQTY=5
-- )-(
-- SELECT TOP 1 b.FQTY
-- FROM xxx AS b
-- WHERE t.fseq <fseq
-- AND FQTY=1
-- ),0)
-- FROM xxx AS t
--将记录1减记录2 ,新增至第3行
INSERT INTO xxx
SELECT ISNULL((
SELECT TOP 1 a.FQTY
FROM xxx AS a
WHERE t.fseq >= fseq
AND FQTY=5
)-(
SELECT TOP 1 b.FQTY
FROM xxx AS b
WHERE t.fseq <fseq
AND FQTY=1
),0),t.fseq
FROM xxx AS t
WHERE fseq=1
SELECT * FROM xxx
DROP TABLE xxx