Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
3.55/5 (4 votes)
Hi All,i have a table with data like this:
C#
Name   Month Number
 XYZ    Jan   2
 XYZ    JAN   4
 XYZ    FEB   6
 XYZ    FEB   2
 XYZ    MAR   10

I want output on month basis as with additional column as:
C#
Name Month Number Count
XYZ   Jan    2       2
XYZ   JAN    4       6
XYZ   FEB    6       6
XYZ   FEB    2       8
XYZ   MAR    10      10

Thanks & Regards
Mohd Wasif
Posted
Updated 1-Dec-13 18:40pm
v2

Here it is :
(I supposed that your table name is Rep)

SQL
with A as
(
SELECT [Name],[Month],[Number]
      ,row_number() over (partition by name , month order by name, month ) rno
  FROM Rep
)
select name , month, number, (
select sum(number) from a a2 where a2.rno<=a1.rno and a2.name=a1.name and a2.month=a1.month ) count
from a a1


Good Luck
 
Share this answer
 
Comments
Maciej Los 2-Dec-13 2:17am    
+5!
Amir Mahfoozi 2-Dec-13 2:22am    
Thank you.
Check my response for similar post. Hope this will give you a reference to fix your issue.

TSQL query (how to update next row from previous row)[^]
 
Share this answer
 
Hello, try this query:

upd:
SQL
SELECT [xyz].[Name], [xyz].[Month], [xyz].[Number], sm.sub_total
  FROM [xyz]
  JOIN (SELECT [Name], [Month], [Number],
               ROW_NUMBER() OVER(ORDER BY [xyz].[Name], [xyz].[Month]) AS pos
          FROM [xyz] ) AS [xyzp]
    ON [xyz].[Name] = [xyzp].[Name] AND
       [xyz].[Month] = [xyzp].[Month] AND
       [xyz].[Number] = [xyzp].[Number]
 OUTER APPLY ( SELECT rn.[Name], [Month], SUM(rn.[Number]) AS sub_total
                 FROM ( SELECT ROW_NUMBER() OVER(ORDER BY [Name], [Month]) AS pos,
                               [Name], [Month], [Number]
                          FROM [xyz]
                       ) AS rn
                 WHERE rn.[Name] = [xyz].[Name] AND
                       rn.[Month] = [xyz].[Month] AND
                       rn.pos <= [xyzp].pos
                 GROUP BY rn.[Name], rn.[Month] ) AS sm


The query would be simplier if to use 'grouping sets' clause, but it only available in MS SQL 2008 or higher.
 
Share this answer
 
v3
Comments
Maciej Los 2-Dec-13 2:14am    
Above query will return sum for each month, but OP wants to get increasing-sum for numbers.
skydger 2-Dec-13 7:54am    
Oops, my mistake, thanks! I've updated solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900