[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 702
  • Last Modified:

How to get previous month in SQL

I have the code shown below that is part of my where clause.  I need to get all data for the previous calendar month, so July 1 - 31 right now since we're in August.  This statement is giving me all July data, but includes multiple years in it.  How can I fix that?

where datepart(m, BEG_DATE) = datepart(m, dateadd(m, -1, getDate()))
and datepart(y, BEG_DATE) = datepart(y, dateadd(m, -1, getDate()))

Open in new window

1 Solution
Vijaya Reddy Pinnapa ReddyCommented:
where beg_date >= dateadd(m, datediff(m, 0, GETDATE()) - 1, 0)
   AND beg_date < dateadd(m, datediff(m, 0, GETDATE()), 0)
fcsITAuthor Commented:

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

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