如何对不同行中两列的值求和 [英] how to sum values of two columns in different rows

查看:80
本文介绍了如何对不同行中两列的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


这篇关于如何对不同行中两列的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆