我有两个表,根据要求我们需要减去下面给出的值。请帮助我解决这个难题....
Table1
MONTH Fee(Advance)
APRIL 5000
Table2
MONTH Fee
MAY 2000
JUNE 300
JULY 1800
AUG 1200
Sep 1500
Expecting Result
ROW 1 MAY 5000(TABLE1.ADVANCE)-2000(TABLE2.FEE)= 3000
ROW 2 JUNE 3000-300 = 2700
ROW 3 JULY 2700-1800 = 900
ROW 4 AUG 900-1200 = -300
ROW 5 Sep -300-1500 = -1800
答案 0 :(得分:0)
我不确定这是否是正确的做法。而不是SQL语句,也许存储过程会有帮助吗?
DECLARE @AdvanceFee INT;
DECLARE @cnt INT = 1;
DECLARE @cnt_total INT = (Select Count(MONTH) From Table2);
SET @AdvanceFee = (Select Fee(Advance) from Table1)
WHILE @cnt <= @cnt_total
BEGIN
Select MONTH, @AdvanceFee = @AdvanceFee - Fee
FROM Table2
WHERE ROW_NUMBER = @cnt
SET @cnt = @cnt + 1;
END
答案 1 :(得分:0)
您需要一个包含月份名称和数字的表格('MAY'= 5,'Sep'= 9,...)。然后使用SUM OVER
获取总计:
select
t.month,
(select fee from table1 where month = 'APRIL') - sum(t.fee) over (order by m.monthnum)
as balance
from table2 t
join months m on m.name = t.month
order by m.monthnum;