How do I query a date range from beginning to end of the previous month in YYYYMMDD format?

I currently have a large amount of SQL queries built for the purpose of Month End reporting.  A common factor in these queries is retrieving total counts in tables between the first and last days of the previous month.  The field in question is BookDate, which is formatted as YYYYMMDD.  

Example:
Say today is March 1st, 2011 (20110301) and I want a total count of transactions in the ActivityHist table that are cash from February 1st, 2011 (20110201) through February 28th (20110228)... (See Attached Code)

Currently, I manually change all BookDate info to reflect the previous month... How can I do this automatically?

Regards,

NCollinsBBP


SELECT COUNT(*)
FROM ActivityHist
WHERE CashTran = '1' AND
      BookDate >= '20110201' AND BookDate <= '20110228'

Open in new window

NCollinsBBPAsked:
Who is Participating?
 
wdosanjosConnect With a Mentor Commented:
Try:

SELECT COUNT(*)
FROM ActivityHist
WHERE CashTran = '1' AND
      left(BookDate,6) = left(convert(varchar(8),dateadd(mm,-1,getdate()),112),6)

Open in new window


I hope this helps.
0
 
lluddenCommented:
To get the first and last day of the previous month,

SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) AS LastDayPrevMonth,
      CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(GETDATE())-1),CAST(GETDATE() as date)),101) AS FirstDayPrevMonth
0
 
lluddenCommented:
If you need this formatted as a string, then use CONVERT to change to YYYYMMDD format,

SELECT CAST(varchar(8),getdate(),112)

0
 
NCollinsBBPAuthor Commented:
If you don't mind, how exactly can I incorporate that into the query I attached?  The BookDate field in my database is plain text and not a datetime field....
0
 
NCollinsBBPAuthor Commented:
Perfection!
This solution gave me the same exact result as my attached query from my original post.
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.

All Courses

From novice to tech pro — start learning today.