如何在单个表中进行交叉添加 [英] How to Get Cross Addition with in the single table
本文介绍了如何在单个表中进行交叉添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好
我有一张类似
的桌子
Hi All
I have a table like
Id Amount
1 10
2 20
3 30
4 40
5 50
我希望输出像
and i want output like
Id Amount Result
1 10 10
2 20 30
3 30 60
4 40 100
5 50 150
ID 1 + 0
ID 2 +结果1
ID 3 +结果2
ID 4 +结果3
ID 5 +结果4
我正在做
ID 1 + 0
ID 2 + Result 1
ID 3 + Result 2
ID 4 + Result 3
ID 5 + Result 4
and i am doing
declare @bb int = 0
select ID,Amount, Amount + @bb Result from My_tbl
但它不起作用
是否可以使用select语句获取输出..
请帮助我
谢谢
but it is not working
Is it Possible to get output using select statement..
Please help Me
Thank You
推荐答案
试试这个:
Try this:
select id, amount,
(select sum(amount) from tablename t2 where t2.id <= t1.id) result
from tablename t1
你可以做类似这样的东西 -
You can do something like this-
SELECT T1.Id, T1.Amount, SUM(T2.Amount) AS Result
FROM YourTable T1
INNER JOIN YourTable T2 ON T1.Id >= T2.Id
GROUP BY T1.Id, T1.amount
ORDER BY T1.Id
示例:
Example:
DECLARE @temp_table AS TABLE(Id INT, Amount INT)
INSERT INTO @temp_table
SELECT 1 Id,10 Amount
UNION
SELECT 2,20
UNION
SELECT 3,30
UNION
SELECT 4,40
UNION
SELECT 5,50
SELECT T1.Id, T1.Amount, SUM(T2.Amount) AS Result
FROM @temp_table T1
INNER JOIN @temp_table T2 ON T1.Id >= T2.Id
GROUP BY T1.Id, T1.amount
ORDER BY T1.Id
希望,它有帮助:)
Hope, it helps :)
这篇关于如何在单个表中进行交叉添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文