Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum the column value incrementally with the same ID column

I am having trouble in querying in SQL Server 2008, I searched the internet but I found nothing or it is not giving me any ideas on how to do it.

Using Northwind database, I need to query the table OrderDetails and select OrderID and UnitPrice showing something like this,

OrderID   -    UnitPrice
------------------------
10248     -     14.00
10248     -     9.80
10248     -     34.80
10249     -     18.60

Result should be:

OrderID   -    UnitPrice
------------------------
10248     -     14.00
10248     -     23.80
10248     -     58.6
10249     -     18.60
like image 728
Markmeplease Avatar asked May 14 '13 04:05

Markmeplease


1 Answers

Please check:

;with T as(
    select 
        *, 
        ROW_NUMBER() over (partition by OrderID order by OrderID) RNum
    from YourTable
)
select 
    *, 
    (select sum(UnitPrice) from T b where b.OrderID=a.OrderID and b.RNum<=a.RNum) CumTotal
From T a

Try in SQL Fiddle

like image 153
TechDo Avatar answered Sep 30 '22 03:09

TechDo