質問

Is it possible to do the following in SQL. I would like to write a code that will return records between certain dates, but will automatically update when the report runs. So for example:

on 12/18 I would like to return records from 11-1 to 11/18 and 12/1 to 12/18 so I can compare month over month on these records in my report.

I understand that I can do:

WHERE
[database] BETWEEN '2013-11-01' and DATEADD(Month, 1, getdate ())) 
and not [database] IN ('2013-11-19 and '2013-11-30')

but I will have to go into the query everyday to update the not between. I would like to make it so that I can run the query on any day and get the records from the previous month up until the date match for this month. I currently have been working with this:

B.[datepaid] between DATEADD(Month, -1, getdate() ) 
and  DATEADD(MONTH, 1,  getdate() ))

but it is returning all records from November.

役に立ちましたか?

解決

I would recommend against using BETWEEN with Dates as it can have some unexpected results. But in your case you can use:

WHERE ([Date] >= DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - 1, '19000101')
AND [Date] < DATEADD(MONTH, -1, GETDATE()))
OR ([Date] >= DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101')
AND [Date] < GETDATE());

Demo on SQL Fiddle

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top