How to Retrieve Records for the Previous Month in SQL Server
When working with a database table containing a timestamp field, it is often necessary to retrieve records for a specific time period, such as the previous month. SQL Server provides various methods to achieve this.
The Problem:
You need to extract records based on a date_created column from the member table where the records fall within the previous month. For example, if the current date is January 3, 2010, you would need to retrieve records from December 1, 2009 to December 31, 2009.
The Challenge:
Some existing solutions encounter issues with ignoring indices or selecting data outside the intended range.
The Correct Approach:
To avoid these pitfalls, the recommended approach utilizes inequality comparison to ensure accurate data retrieval. Here's the corrected query:
DECLARE @startOfCurrentMonth DATETIME SET @startOfCurrentMonth = DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0) SELECT * FROM Member WHERE date_created >= DATEADD(month, -1, @startOfCurrentMonth) AND date_created < @startOfCurrentMonth
This method calculates the start of the current month and employs inequality comparison to include records for the previous month only. By using indices and avoiding unnecessary comparisons, this approach delivers efficient and accurate results.
The above is the detailed content of How to Efficiently Retrieve Last Month's Records in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!