如何对不同行中两列的值求和
问题描述:
HI,
SELECT MONTH(Month) AS Month ,
SUM(vlera) AS Value ,
SUM(0) AS [Don't know how to do]
FROM dbo.tblTest
GROUP BY MONTH(Month)
Month Value Don't know how to do
----------- ------------- --------------------
1 12.50 0
2 12.50 0
3 12.50 0
4 13.00 0
谁能让我知道如何在不同的行中选择第二和第三列的总和,在此示例中,第三列应包含:
Could anybody let me know how to select sum of second and third columns in different rows, in this example the third column should contain:
12.5
25
37.5
50.5
提前感谢
Thanx in advance
答
尝试使用应用"运算符
Try using "apply" operator
SELECT
t.Month AS Month ,
t.vlera AS Value ,
tt.column_total AS [sub total]
FROM dbo.tblTest t
cross apply
(select sum(vlera) as column_total
from tblTest
) as tt
ORDER BY t.Month
另请参见以下链接以了解不同的选项:
http://stackoverflow.com/questions/860966/calculate-a-running-total- in-sqlserver [ ^ ]
also see the following link for different options:
http://stackoverflow.com/questions/860966/calculate-a-running-total-in-sqlserver[^]
^ ]
http://www.sqlteam.com/article/calculating-running-totals [ ^ ]
calculating-running-totals-in-sql-server-2005[^]
http://www.sqlteam.com/article/calculating-running-totals[^]
尝试此查询,
try with this query,
SELECT a.month,
a.value,
SUM(b.value) as cumulativesum
FROM #temp a,
#temp b
where (b.month <= a.month)
GROUP BY a.month,a.value
问候
pal
regards
pal