Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 339
  • Last Modified:

get max date record entered in previous month

Hello
I have a table where I extract data for a given day - I want to compare this data with data from previous month - but only the data for the last entry for the previous month - how would I do this?

0
modish
Asked:
modish
  • 2
  • 2
2 Solutions
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
select * from yourtable
where yourfield = ( select max ( yourfield ) from yourtable where yourfield <= dateadd(day, 1 - datepart(day, getdate()), convert(datetime, convert(varchar(10), getdate(), 120), 120) )   )
0
 
Aneesh RetnakaranDatabase AdministratorCommented:
select top 1 *
from urTable  WHERE urDateColumn < CAST(CONVERT(Varchar(6), GETDATE(),112)+'01' as Datetime)
ORDER BY urDateColumn DESC
0
 
modishAuthor Commented:
Apologies for the late response
thanks to you both for your responses - I couldn't get aneeshattingals one to work  problem with casting.- but angelIII worked brilliantly -
I changed it to be
 yourfield <= dateadd(day,  - datepart(day, getdate()), convert(datetime, convert(varchar(10), getdate(), 120), 120) )  
to get the last day of the previous month ..
Is this the best way to do the same for the month before that.
yourfield <=  dateadd(month,-1,dateadd(day, 1 - datepart(day, getdate()), convert(datetime, convert(varchar(10), getdate(), 120), 120) )   )

0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
yes. the dateadd(month, -1) ... will take care of any 31/30/29/28 days per month.
0
 
modishAuthor Commented:
Excellent and aneeshattingal solution worked as well :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now