Sum the value of the column with the same identifier column

I am having problems with queries in SQL Server 2008, I searched the Internet, but did not find anything or did not give me any ideas on how to do this.

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

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

The result should be:

 OrderID - UnitPrice ------------------------ 10248 - 14.00 10248 - 23.80 10248 - 58.6 10249 - 18.60 
+6
source share
2 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 SQL Fiddle

+5
source

May refer as follows:

 SELECT t1.id, t1.unitprice, SUM(t2.unitprice) AS SUM FROM t t1 INNER JOIN t t2 ON t1.id >= t2.id GROUP BY t1.id, t1.unitprice ORDER BY t1.id 

Demo:

SQLFIDDLE DEMO

-2
source

Source: https://habr.com/ru/post/944944/


All Articles