如何从我的销售表中获取累积列?

时间:2013-08-26 17:00:08

标签: sql sql-server

我有以下情况

pid& month形成复合主键。

pid month amount
1    1     10
2    2     15
1    2     20
1    3     10
3    3     4
2    3     6

现在使用表格生成的列将是这样的

pid month amount   sum
1    1     10      10
2    2     15      15
1    2     20      30
1    3     10      40
3    3     4       4
2    3     6       21

查询应该是什么?

3 个答案:

答案 0 :(得分:2)

如果使用SQL Server 2012:

SELECT *,SUM(amount) OVER(PARTITION BY pid ORDER BY month ROWS UNBOUNDED PRECEDING)'Total'
FROM YourTable

答案 1 :(得分:2)

此查询可以解决问题:

SELECT t1.*, sum(t2.amount)
FROM Table1 t1
INNER JOIN Table1 t2 ON t1.pid = t2.pid AND t1.month >= t2.month
GROUP BY t1.pid, t1.month, t1.amount

请参阅SQLFIDDLE:http://www.sqlfiddle.com/#!3/db350/7/0

答案 2 :(得分:1)

您没有指定正在使用的SQL Server版本,但您应该能够使用以下内容获取任何版本的运行总计:

select t1.pid, 
  t1.month, 
  t1.amount,
  (select sum(t2.amount) 
   from yourtable t2
   where t1.pid = t2.pid
     and t2.month <= t1.month) total
from yourtable t1;

请参阅SQL Fiddle with Demo