Hello, I have a simple problem that I can't seem to figure out.
I have a table (tblTrans) that has records from the past 3 years. Each record is dated (TransDate). I need a Select Statement that will give me all of the records for the month prior to the current month. This is easy enough except when the prior month is December and the year is the previous year. For example;
SELECT t.*
FROM Transdate t
WHERE MONTH(TransDate) = MONTH(GETDATE() - DATEPART(d, GETDATE()))
AND YEAR(TransDate) = YEAR(GETDATE())
This statement works fine if the current Month is February thru December. But if the current month is January then I need to switch the year back to the previous year to access those records. I'm sure I need to modify the "Year" section in the WHERE clause. I just can't figure it out. This must be done in the select clause. I cannot do it in a stored procedure or with multiple SQL statements.
Thank you.
I have a table (tblTrans) that has records from the past 3 years. Each record is dated (TransDate). I need a Select Statement that will give me all of the records for the month prior to the current month. This is easy enough except when the prior month is December and the year is the previous year. For example;
SELECT t.*
FROM Transdate t
WHERE MONTH(TransDate) = MONTH(GETDATE() - DATEPART(d, GETDATE()))
AND YEAR(TransDate) = YEAR(GETDATE())
This statement works fine if the current Month is February thru December. But if the current month is January then I need to switch the year back to the previous year to access those records. I'm sure I need to modify the "Year" section in the WHERE clause. I just can't figure it out. This must be done in the select clause. I cannot do it in a stored procedure or with multiple SQL statements.
Thank you.