0

I have a table in sql server and I want to summarize a cell with upper rows in T-Sql like this:

 Quantity          Total
-----------------------------
    1                1
    5                6
    12               18
    20               38

I use SQL server 2008, How can I achieve this?

Regards, Majid.

Majid Hosseini
  • 1,098
  • 10
  • 17

1 Answers1

0

You are looking for a cumulative sum, it would appear. If you are using SQL Server 2012 or later, just do:

select quantity, sum(quantity) over (order by quantity)
from table t;

Note the order by quantity. You need to specify the ordering for the cumulative sum, typically doing another sum.

In earlier versions, you can do this using a correlated subquery:

select quantity,
       (select sum(t2.quantity)
        from table t2
        where t2.quantity <= t.quantity
       ) as total
from table t;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • I'm using SQL server 2008 – Majid Hosseini Jul 07 '14 at 15:11
  • @MajidHosseini you should have mentioned that right from the beginning. Than Gordon wouldn't have shown you a solution that does not apply to your version. –  Jul 07 '14 at 15:17
  • @a_horse_with_no_name . . . Actually, I was interrupted before I could finish the answer. I do wonder why my original answer was downvoted, because it did explicitly state the version issue. Alas. – Gordon Linoff Jul 07 '14 at 15:32