--1. 將結果插入臨時表SELECT *INTO xxx FROM( SELECT TOP 1 a.FQTY,a.fseq FROM T_SAL_ORDERENTRY as a WHERE FQTY=5UNION ALL SELECT TOP 1 b.FQTY,b.fseq FROM T_SAL_ ...
--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