Вопрос

SELECT *

FROM 
  [Test].[dbo].[Tickets]

INNER JOIN 
  [Test].[dbo].[Movies]

ON 
  [Test].[dbo].[Tickets].[ConnectedTo] = [Test].[dbo].[Movies].[MovieID]

WHERE
  [Test].[dbo].[Movies].[Moviename] like '%K%'
  AND [Test].[dbo].[Tickets].[DateEntered]= DATEADD(month, -1, GETDATE())

I am attempting to create a stored procedure that will always return every ticket from the previous month based on the column DateEntered. This line however doesn't seem to ever return data however:

[Test].[dbo].[Tickets].[DateEntered]= DATEADD(month, -1, GETDATE())

I believe the logic behind it is correct in the way that it will grab the current date, change it to the previous month and then compare that date with DateEntered, though I could be mistaken here. Any help would be much appreciated.

Это было полезно?

Решение

Just replace = with >=

[Test].[dbo].[Tickets].[DateEntered] >= DATEADD(month, -1, GETDATE())

Your current condition would look only for rows where DateEntered is exactly (in miliseconds) one month ago :)

Другие советы

I'm not sure if the selected answer is the best method to achieve this. If you ran the report on the 13th of the month, it would only give you every record from the 13th of the previous month until the exact time the report was ran.

Thus you want something similar to this. You need to be careful if the month is January because then we want the previous year as well as the previous month.

-- If the month is January we need to select the previous year, otherwise current year
IF MONTH(GETDATE()) = 1
    BEGIN
        YEAR([DateEntered]) = YEAR(DATEADD(y, -1, GETDATE())) AND MONTH([DateEntered]) = MONTH(DATEADD(m, -1, GETDATE())
    END
ELSE
    BEGIN
        YEAR([DateEntered]) = YEAR(GETDATE()) AND MONTH([DateEntered]) = MONTH(DATEADD(m, -1, GETDATE())
    END
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top