Ryan Gadsdon
Ryan Gadsdon

Reputation: 2378

Returning Previous Months Data Across Year Boundary - SQL Server

Fiddle: http://sqlfiddle.com/#!18/5d05a/3

I have tables:

CREATE TABLE Table1(
Date Date,
Figure int
);

INSERT INTO Table1 (Date, Figure)
VALUES ('06-06-18','25'),
('05-12-18','30'),
('05-27-17','30');

I am using this query to return the previous months data

DECLARE @PrevMonth int = MONTH(getdate()) -1,
@Year int = YEAR(getdate())


SELECT @Year AS [Year], @PrevMonth AS [Month], Figure
FROM Table1
WHERE MONTH([Date]) = @PrevMonth
AND YEAR([Date]) = @Year

Which returns:

| Year | Month | Figure |
|------|-------|--------|
| 2018 |     5 |     30 |

However, this wont work once i hit Jan of a new year. In Jan of that new year i would be looking for December of the previous year. Can anyone advise me on a better method to use which would cover Jan in a new year. Thanks

Upvotes: 2

Views: 77

Answers (2)

Thom A
Thom A

Reputation: 95557

Querying the month and year parts of a query is a great way to slow it down. You're far better off with the date manipulation on the input parameter (in this case GETDATE()) not the column:

SELECT *
FROM Table1
WHERE [Date] >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1,0)
  AND [date] < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()),0);

Upvotes: 3

EzLo
EzLo

Reputation: 14189

Don't use functions on your table's columnns (it makes them non-SARGable and can't use indexes properly). You can use a good date filter instead.

DECLARE @StartDate DATE = DATEADD(DAY, 1,EOMONTH(GETDATE(), - 2))
DECLARE @EndDate DATE = DATEADD(DAY, 1,EOMONTH(GETDATE(), -1))

SELECT Figure FROM Table1
WHERE [Date] >= @StartDate AND [Date] < @EndDate

Upvotes: 1

Related Questions