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
 General SQL Server Forums
 New to SQL Server Programming
 sql syntax for months

Author  Topic 

Trininole
Yak Posting Veteran

83 Posts

Posted - 2011-04-26 : 12:19:18
how to display the months in sql in a select statement?

like from July 2010 till March 2011?

Roger DeFour

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2011-04-26 : 12:22:52
not sure what you mean - maybe

;with cte as
(
select dte = convert(datetime,'20100701')
union all
select dte = DATEADD(m,1,dte) from cte where dte < '20110301'
)
select dte, DATEPART(year,dte), DATENAME(mm,dte)
from cte


==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

Trininole
Yak Posting Veteran

83 Posts

Posted - 2011-04-26 : 12:25:17
I am trying to retrieve counts for each month from July till march. What is the syntax for that?


Roger DeFour
Go to Top of Page

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2011-04-26 : 12:37:26
select convert(varchar(6),dte), count(*)
from tbl
where convert(varchar(6),dte) between '201007' and '201103'

or if you want to cater for zero counts

;with cte as
(
select dte = convert(datetime,'20100701')
union all
select dte = DATEADD(m,1,dte) from cte where dte < '20110301'
)
select cte.dte, sum(case when tbl.dte is null then 0 else 1 end)
from cte
left join tbl
on datediff(mm,tbl.dte,cte.dte) = 0
group by cte.dte


==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page
   

- Advertisement -