我在表格中有Store_ID
个手续付款,需要根据transactions_id
的{{1}}结算/调整付款。
可以按如下方式创建表:
store_id
调整付款的顺序可能基于RECEIPT_NO订单或rowid。
突出显示列中的必需输出:
答案 0 :(得分:0)
BEGIN TRAN
--CREATE #STORE_PAYMENTS TABLE--- CONTAINS RECEIVABLE AGAINST RECEIPTS NOS FOR STROES-------
CREATE TABLE #STORE_PAYMENTS (STORE_ID VARCHAR(10) NOT NULL, RECEIPT_NO VARCHAR(10) NOT NULL, RECEIVABLE INT NOT NULL, PAYMENTS INT NOT NULL, BALANCE INT NOT NULL)
GO
INSERT INTO #STORE_PAYMENTS (STORE_ID,RECEIPT_NO,RECEIVABLE,PAYMENTS,BALANCE)
SELECT 'STR1',1,100,0,0 UNION ALL
SELECT 'STR1',2,200,0,0 UNION ALL
SELECT 'STR1',3,300,0,0 UNION ALL
SELECT 'STR2',1,200,0,0 UNION ALL
SELECT 'STR2',2,300,0,0 UNION ALL
SELECT 'STR2',3,400,0,0 UNION ALL
SELECT 'STR3',1,0,0,0 UNION ALL
SELECT 'STR3',2,150,0,0 UNION ALL
SELECT'STR3',3,300,0,0
--CREATE STORE_BALANCE TABLE --- CONTAINS INFORMATION OF IN HAND PAYMENTS -----------------
CREATE TABLE #STORE_BALANCE (STORE_ID VARCHAR(10) NOT NULL, PAYMENTS INT NOT NULL,TMP_PAYMENTS INT NOT NULL)
INSERT INTO #STORE_BALANCE
SELECT 'STR1',500,500 UNION ALL
SELECT 'STR2',700,700 UNION ALL
SELECT 'STR3',300,300
SELECT ROW_NUMBER()Over(Order by Store_ID)RowNum,* INTO #T FROM #STORE_BALANCE --Order by RowNum desc
SELECT DENSE_RANK()OVER(Order by STORE_ID)RANK, ROW_NUMBER()Over(Order by Store_ID)RowNum, * INTO #TT FROM #STORE_PAYMENTS
Declare @strt INT ,@End INT
SELECT TOP 1 @strt=RowNum FROM #t
SELECT @End=MAX(RowNum) FROM #t
While @strt<=@End
Begin
DECLARE @RANK INT=1,@Rownum INT,@Payments INT,@RECEIVABLE INT,@Total_RECEIVABLE INT
SELECT @Rownum=MAX(RECEIPT_NO)FROM #TT WHERE RANK=@strt
WHILE @RANK<=@Rownum
BEGIN
SELECT @Payments=Tmp_Payments FROM #T WHERE RowNum=@strt
SELECT @RECEIVABLE=RECEIVABLE FROM #TT WHERE RANK=@strt AND RECEIPT_NO =@RANK
IF @Payments >= @RECEIVABLE
Begin
UPDATE #TT SET PAYMENTS=@RECEIVABLE WHERE RANK=@strt AND RECEIPT_NO = @RANK
UPDATE #T SET TMP_PAYMENTS=@Payments-@RECEIVABLE
FROM #t Inner Join #tt ON #t.RowNum=#TT.RANK
WHERE RECEIPT_NO=@RANK AND RANK=@strt
END ELSE BEGIN
UPDATE #TT SET PAYMENTS =@Payments WHERE RANK=@strt AND RECEIPT_NO = @RANK
SELECT @Total_RECEIVABLE=SUM(Payments) FROM #TT WHERE RANK=@strt
UPDATE #T SET TMP_PAYMENTS = @Total_RECEIVABLE-@Payments
FROM #t Inner Join #tt ON #t.RowNum=#TT.RANK
WHERE RANK=@strt AND RECEIPT_NO=@RANK
END
-- Select * from #TT WHERE RANK=@strt AND RECEIPT_NO = @RANK
SET @RANK=@RANK+1
END
SET @strt=@strt+1
END
UPDATE #STORE_PAYMENTS SET PAYMENTS=T.PAYMENTS,BALANCE=T.RECEIVABLE-T.PAYMENTS
FROM #STORE_PAYMENTS S INNER JOIN #TT T ON S.STORE_ID=T.STORE_ID AND S.RECEIPT_NO=T.RECEIPT_NO
SELECT * FROM #STORE_PAYMENTS
ROLLBACK TRAN