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.
| Author |
Topic |
|
eirikr_1
Starting Member
27 Posts |
Posted - 2010-02-10 : 14:57:33
|
| can any one help me with this problemi have a database column named dateStr (yyyymmdd)200912012009120220091203 should returns count=3 for Dec200911012009110220091103 count=3 for Nov200910012009100220091003 count=320081201 count=120081101 count=12008100120081002 count=2I need a query to count number of month.Please Help |
|
|
shan
Yak Posting Veteran
84 Posts |
Posted - 2010-02-10 : 15:16:57
|
| See if this works for you...declare @i table (dt varchar(10))insert into @i select('20091201')union allselect('20091202')union allselect('20091203')union allselect('20091101')union allselect('20091102')union allselect('20091103')union allselect('20091001')union allselect('20091002')union allselect('20091003')union allselect('20081101')union allselect('20081001')union allselect('20081002')select substring(dt,1,6) MTH,MAX(substring(dt,7,8)) MAX_DT from @igroup by substring(dt,1,6) order by substring(dt,1,6) -Shan |
 |
|
|
eirikr_1
Starting Member
27 Posts |
Posted - 2010-02-10 : 15:21:52
|
| It works perfectly. Thank you very much Shan |
 |
|
|
shan
Yak Posting Veteran
84 Posts |
Posted - 2010-02-10 : 15:32:33
|
| you are welcome-Shan |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2010-02-11 : 00:24:27
|
quote: Originally posted by shan See if this works for you...declare @i table (dt varchar(10))insert into @i select('20091201')union allselect('20091202')union allselect('20091203')union allselect('20091101')union allselect('20091102')union allselect('20091103')union allselect('20091001')union allselect('20091002')union allselect('20091003')union allselect('20081101')union allselect('20081001')union allselect('20081002')select substring(dt,1,6) MTH,MAX(substring(dt,7,8)) MAX_DT from @igroup by substring(dt,1,6) order by substring(dt,1,6) -Shan
why have you declared a varchar field to store dates?Always use proper datatype for your fieldsStoring date values as varchar makes date manipulations difficultfor month grouping there's no need to convert it to varchar. you can simply do likeSELECT DATEADD(mm,DATEDIFF(mm,0,datefield),0),COUNT(*)FROM tableGROUP BY DATEADD(mm,DATEDIFF(mm,0,datefield),0) and formatting you can do at front end------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|
|