Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Running Totals Across Months / Years

Author  Topic 

mtcoder
Starting Member

19 Posts

Posted - 2010-08-13 : 15:53:41
I have a table which keeps track if a member is active or not and the date they became active. I am trying to get a count of how many people activated for each month in each year. That part I have down. The part I am having trouble with is I also need to have a "running Total" of all active members at each month and year.

Here is the code for the number of actives by month / year grouping.

select count(distinct md.Member_ID) as MembersActive,datepart(month,active_date) as MonthActive, datepart(year,active_date) as YearActive
from e911_member_detail as md
where md.status_ID = 5 and datepart(year,active_date) in ('2008','2009','2010')
group by datepart(year,active_date), datepart(month,active_date)
order by datepart(year,active_date), datepart(month,active_date)


Gives me
MembersActive MonthActive YearActive
1 2 2008
1 3 2008
9 9 2008
7 1 2009
28 2 2009

Which is great for the first part, number of members activated by month / year.

What I also need though is
MembersActive MonthActive YearActive
1 2 2008
2 3 2008
11 9 2008
18 1 2009
46 2 2009

aka the running total, by month/year. Ideally with a datefield like 2/1/2008 instead of month active / year active. So I can graph it in excel. But I'm not picky, and can work around the datefield part.

Thank you

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-08-14 : 01:23:30
[code]
;With Member_CTE (MembersActive,MonthActive,YearActive)
AS
(
select count(distinct md.Member_ID) as MembersActive,datepart(month,active_date) as MonthActive, datepart(year,active_date) as YearActive
from e911_member_detail as md
where md.status_ID = 5 and datepart(year,active_date) in ('2008','2009','2010')
group by datepart(year,active_date), datepart(month,active_date)
)

SELECT m1.MemberActive,m1.MembersActive + m2.PrevMembers AS RunningCnt,m1.MonthActive,m1.YearActive
FROM Member_CTE m1
CROSS APPLY (SELECT SUM(MembersActive) AS PrevMembers
FROM Member_CTE
WHERE YearActive <m1.YearActive
OR (YearActive = m1.YearActive AND MonthActive < m1.MonthActive)
)m2
order by m1.YearActive,m1.MonthActive
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -