0

I have the following scenario

pid & month form a composite primary key .

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

Now the column to be generated with the table will be like this

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

What should be the query ?

4

3 回答 3

2

如果使用 SQL Server 2012:

SELECT *,SUM(amount) OVER(PARTITION BY pid ORDER BY month ROWS UNBOUNDED PRECEDING)'Total'
FROM YourTable
于 2013-08-26T17:10:08.820 回答
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

于 2013-08-26T17:11:41.340 回答
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

于 2013-08-26T17:09:20.137 回答