这是我的sql代码:
CREATE TABLE #tmp
(
Id INT IDENTITY(1, 1) ,
Amount MONEY ,
Rate FLOAT ,
NetAmount MONEY
);
CREATE TABLE #rate ( Rate FLOAT );
INSERT INTO #rate
( Rate )
VALUES ( 1.2 );
-- Rate - float
INSERT INTO #rate
( Rate )
VALUES ( 1.3 -- Rate - float
);
INSERT INTO #rate
( Rate )
VALUES ( 1.5 -- Rate - float
);
DECLARE @Amount MONEY = 5000;
INSERT INTO #tmp
( Amount ,
Rate ,
NetAmount
)
SELECT @Amount ,
r.Rate ,
r.Rate * @Amount
FROM #rate AS r;
SELECT *
FROM #tmp AS t;
DROP TABLE #rate;
DROP TABLE #tmp;
这是我的输出:
Id Amount Rate NetAmount
----------- --------------------- ---------------------- ---------------------
1 5000.00 1.2 6000.00
2 5000.00 1.3 6500.00
3 5000.00 1.5 7500.00
我需要这样的输出:
Id Amount Rate NetAmount
----------- --------------------- ---------------------- ---------------------
1 5000.00 1.2 6000.00
2 6000.00 1.3 7800.00
3 7800.00 1.5 11700.00
正如您所看到的,第一个金额5000.00作为参数被接收,然后有一个按特定顺序定义的费率列表。我需要在你所需的输出中看到每个费率。第一个NetAmount成为下一行的金额。
我想在不使用游标或while循环的情况下实现此目的。
答案 0 :(得分:0)
只需添加Computed column,然后将输出中的魔法视为
CREATE TABLE #tmp
(
Id INT IDENTITY(1, 1) ,
Amount MONEY ,
Rate FLOAT ,
NetAmount AS Amount * Rate -- computed column
);
CREATE TABLE #rate ( Rate FLOAT );
INSERT INTO #rate
( Rate )
VALUES ( 1.2 );
-- Rate - float
INSERT INTO #rate
( Rate )
VALUES ( 1.3 -- Rate - float
);
INSERT INTO #rate
( Rate )
VALUES ( 1.5 -- Rate - float
);
DECLARE @Amount MONEY = 5000;
INSERT INTO #tmp
( Amount ,
Rate
--, NetAmount
)
SELECT @Amount ,
r.Rate
--,r.Rate * @Amount
FROM #rate AS r;
SELECT *
FROM #tmp AS t;
DROP TABLE #rate;
DROP TABLE #tmp;
答案 1 :(得分:0)
您需要累积的费率产品。但是,没有内置功能来实现这一点。您可以使用LOG
和EXP
以及累计SUM
来实现此目的:
insert into #tmp (amount, rate, netamount)
select lag(netamount, 1, @Amount) over (order by id) as amount,
rate,
netamount
from (
select id,
@amount * exp(sum(log(rate)) over (order by id)) as netamount,
rate
from #rate
) t;
这假设您在费率表中有一个ID列,您想要按照其应用的费率和计算的金额。 记住,RDBMS中没有内在的顺序。