The main method is to use the aggregation function to realize the sum value of a column by row by self-join.
This is before the statistics
After the statistics, the result is
The implementation code is as follows:
1 Create TableSales2 ( 3ProductNamenvarchar( -) 4, Dateofmonthnvarchar( -)5, quantityint 6 )7 8 Insert intoSales9 Select 'P1','201401', -Ten Union All One Select 'P1','201402', - A Union All - Select 'P1','201403', - - Union All the Select 'P2','201401', $ - Union All - Select 'P2','201402', - - Union All + Select 'P2','201403', - - Union All + Select 'P2','201401', - A Union All at Select 'P3','201402', - - Union All - Select 'P3','201403', - - - --SELECT * FROM Sales - in SelectRow_number () Over(Order byproductname,dateofmonth,quantity) SID,* - into#Temp to fromSales + - --SELECT * from #temp the SelectDense_rank () Over(Order byProductName) RID,* * into#temp1 $ from#TempPanax Notoginseng - Select the A.productname + , A.dateofmonth A , A.quantity the,sum(b.quantity) as Total + from#temp1 A, #temp1 b - whereA.sid>=B.sid andA.rid=B.rid $ Group byA.productname,a.dateofmonth,a.quantity
T-SQL applies self-join row-by-line statistics sum value