sql - select total count() group by year and month? -


for example imagine table below

select accountid, createdon account  73c56f61-5ff1-e111-a4f8-005056977fbc    2012-08-28 22:26:47.000 a7c56f61-5ff1-e111-a4f8-005056977fbc    2012-08-28 22:26:48.000 b7c56f61-5ff1-e111-a4f8-005056977fbc    2012-08-28 22:26:48.000 fbc56f61-5ff1-e111-a4f8-005056977fbc    2012-08-28 22:26:49.000 cbc66f61-5ff1-e111-a4f8-005056977fbc    2012-08-28 22:26:54.000 87c66f61-5ff1-e111-a4f8-005056977fbc    2012-08-28 22:26:53.000 53c76f61-5ff1-e111-a4f8-005056977fbc    2012-08-28 22:26:55.000 87c76f61-5ff1-e111-a4f8-005056977fbc    2012-08-28 22:26:56.000 2ed89924-5cfc-e111-a4f8-005056977fbc    2012-09-11 22:01:51.000 c0d79924-5cfc-e111-a4f8-005056977fbc    2012-09-11 22:01:49.000 

then in january 2012 count 10 accounts query

select count(*) account 

let's have 5 new accounts in february 2012, querying count(*) in february 2012 returns 15 accounts. if have 10 new accounts in march 2012, then querying count(*) in march 2012 returns 35 accounts in total.

i'd below results

2012-january-10 accounts 2012-febrary-15 accounts 2012-march-  35 accounts 

creation date in table account date,

but if query

select year(createdon), month(createdon), count(*) quantity accounts group year(createdon), month(createdon) 

i below result instead:

2012-january-10 accounts 2012-febrary-5 accounts 2012-march-  20 accounts 

then how can first result simple query? not loops

you need rolling total. there're several way in sql server(see calculate running total in sql server), sql 2005 simplest(not fastest) way self join

with cte (     select         datename(year, createdon) + '-' + datename(month, createdon) name,         convert(nvarchar(6), createdon, 112) grp,         count(*) cnt     account     group         datename(month, createdon), datename(year, createdon),         convert(nvarchar(6), createdon, 112) ) select     c1.name, sum(c2.cnt) cnt cte c1     inner join cte c2 on c2.grp <= c1.grp group c1.name 

sql fiddle demo


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -