使用当前行中的字段将增加应用到上一行
我有一个像这样设置的临时表:
Type Rate TotalCost
---- ---- ---------
Type1 0.01 3276.00
Type2 0.01 3276.00
Type3 0.01 3276.00
但是,我需要获取当前行的速率,将其乘以之前的总计,然后将其添加到当前总计......以得出新的总计!
Type Rate TotalCost
---- ---- ---------
Type1 0.01 3276
Type2 0.01 3308.76
Type3 0.01 3341.85
所以 3276 的 1% 是 32.76。
3276 + 32.76 = 3308.76。
3308 的 1% 是 33.08。
3308.76 + 33.08 = 3341.85。
等等。
我尝试创建一个 CTE,就像这样
;with cte
as
(
select Type, Rate, TotalCost, row_number() over (order by SortOrder asc) as RowNum
from @Types
)
select cur.RowNum, cur.Rate, prev.Rate, cur.TotalCost, isnull(prev.TotalCost * cur.Rate, cur.TotalCost) as NewTotal
from cte cur
left join cte prev on prev.RowNum = cur.RowNum + 1
......但它不起作用:(
任何人都可以帮忙吗?
我正在使用 SQL Server 2005!
提前致谢!
I have a temp table set up like this:
Type Rate TotalCost
---- ---- ---------
Type1 0.01 3276.00
Type2 0.01 3276.00
Type3 0.01 3276.00
However, I need to take the rate of the current row, times it by the previous total, then add it to the current total...to come up with the new total!
Type Rate TotalCost
---- ---- ---------
Type1 0.01 3276
Type2 0.01 3308.76
Type3 0.01 3341.85
So 1% of 3276 is 32.76.
3276 + 32.76 = 3308.76.
1% of 3308 is 33.08.
3308.76 + 33.08 = 3341.85.
And so on.
I tried creating a CTE, like so..
;with cte
as
(
select Type, Rate, TotalCost, row_number() over (order by SortOrder asc) as RowNum
from @Types
)
select cur.RowNum, cur.Rate, prev.Rate, cur.TotalCost, isnull(prev.TotalCost * cur.Rate, cur.TotalCost) as NewTotal
from cte cur
left join cte prev on prev.RowNum = cur.RowNum + 1
...but it's not working :(
Can anyone help?
I'm using SQL Server 2005!
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从您的示例结果来看,您似乎正在对所有以前的行进行求和,而不仅仅是最后一行。您可以在没有 CTE 的情况下做到这一点,例如:
一个问题是示例数据中没有排序顺序。我在这里按类型排序;我希望您的真实表格中有更好的排序顺序!
另一个问题是只有第一行的
TotalCost
很重要。对于以下行,成本是根据第一行的成本和其他行的费率得出的。From your example results, it looks like you're summing all previous rows, instead of just the last one. You can do that without a CTE, like:
One problem is that there's no sort order in your example data. I'm sorting on type here; I'm hoping there's a better sort order in your real table!
Another problem is that only the
TotalCost
of the first row matters. For the following rows, the cost is derived from the first rows' cost, and other rows' rate.我发现最好的方法是编写一个循环:
The best way I've found is to write a loop: