我尝试在sql server中查询但结果未生成
我的查询,表格和预期结果提及
USE [bank]
GO
/****** Object: StoredProcedure [dbo].[Pr_Rpt_BankPlaning] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PRODCEDURE [dbo].[Pr_Rpt_BankPlaning] AS
BEGIN ;
WITH cte AS
(
SELECT
TotalAmount,
BankAmount,
(TotalAmount-BankAmount) AS minusamount,
rownum = ROW_NUMBER() OVER (order BY BankAmount)
FROM Bank AS bc
)
SELECT
CASE
WHEN cte.TotalAmount = prev.TotalAmount THEN prev.minusamount
ELSE cte.TotalAmount
END AS TotalAmount1,
cte.BankAmount,
CASE
WHEN cte.TotalAmount = prev.TotalAmount THEN prev.minusamount
ELSE cte.TotalAmount
END
-cte.BankAmount AS Amount,
cte.minusamount,
cte.rownum
FROM CTE
LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
LEFT JOIN CTE nex ON nex.rownum = CTE.rownum + 1
END
答案 0 :(得分:1)
虽然您还没有按照其他人的要求提供任何样本数据,但我使用了第一个屏幕截图中显示的输出作为样本数据来为您提供所需的输出。您需要在查询中集成我的CTE才能获得输出。
以下查询为您提供所需的输出。
DECLARE @AMOUNT_DATA TABLE(TA INT, BA INT,AM INT,MAMT INT,ROWNUM INT )
INSERT INTO @AMOUNT_DATA VALUES
(458800,25000,433800,433800,1),
(433800,25000,408800,433800,2),
(433800,100000,333800,358800,3)
;WITH AMOUNT_DATA
AS
(
SELECT ROWNUM,TA,BA,TA-BA RESULT FROM @AMOUNT_DATA WHERE ROWNUM=1
UNION ALL
SELECT T2.ROWNUM,T1.RESULT TA,T2.BA,T1.RESULT-T2.BA FROM AMOUNT_DATA T1
JOIN @AMOUNT_DATA T2 ON T1.ROWNUM=T2.ROWNUM-1
)
SELECT * FROM AMOUNT_DATA
输出
------------------------------
--ROWNUM TA BA RESULT
------------------------------
1 458800 25000 433800
2 433800 25000 408800
3 408800 100000 308800
------------------------------