So if you want only the data from the month that was 6 months ago, use equal instead of less than:
select datetimeInsert, Part_no,qty
from receipt
where datediff(month, datetimeInsert, getdate()) = 6
EDIT 1: A good point from @larnu is that the use of the datetimeInsert
column inside the DATEDIFF()
function makes this query less sargeable, i.e. it won't be able to take advantage of using indices.
You can achieve the same like this without sacrificing sargeability:
select datetimeInsert, Part_no,qty
from receipt
where datetimeInsert >= DATEADD(DAY, 0, DATEDIFF(DAY, 0, DATEADD(MONTH, -7, GETDATE())))
and datetimeInsert < DATEADD(DAY, 0, DATEDIFF(DAY, 0, DATEADD(MONTH, -6, GETDATE())));
Note: I'm just realizing that this second query does not just look at the month, but a the period that was between 7 and 6 months ago. So you will be getting the results from exactly 7 to 6 months ago, not the ones that are in the month that was 6 before the current month. If you want the latter (which is actually the same as your original query in the question) you'll find the solution in @larnu's answer.
EDIT 2: As commented by @Jeff, the time boundaries when using an expression like DATEADD(MONTH, -7, GETDATE())
will be those of a datetime exactly 7 months ago as of today at this exact time. I've updated both the statement above and the dbfiddle below to remedy that and highlight the difference.
See db<>fiddle.