开发者

How to do the difference from yyyy/mm using month?

I have a column called [date] and the data in that column is something like this:

[date]

2011/01
2011/02
2011/03
2011/04
2011/05
2011/06
2011/07
2011/08
2011/09
2011/10

My full scenario is that I have created a column named [date] and I am dumping the data to that column from another column called [fiscal_month] (both are from same table).

I have to retrieve the latest 9 months data from that [date] column and I have written this code:

SELECT TOP 9 REPLACE (P.[Fiscal Month],'M'开发者_C百科,'/') as [date],
      P.[Fiscal Month] AS [Fiscal Month] FROM [OR].[Report].[SD_P] P 
WHERE [date] <= CONVERT(char(7), GETDATE(), 111) ORDER BY [date] DESC 

The [fiscal_month] column is VARCHAR(100).

The data in the [fiscal_month] column is something like this:

2011M01,2011M02, 2011M03, 2011M04, 2011M05
etc

Update:

I altered the [date] column and I have assigned the datetime datatype for that column and then I select into it with the replacement of 'M' from the other column with '/' to get the 9 months latest data..


I'm assuming that the date column is actually stored as text. If that's the case, the easiest solution is to convert it to a datetime and then do your comparison:

Select ...
From MyTable
Where Cast(Replace([Date],'/','') + '01' As DateTime)
    > DateAdd(m, -9
         , DateAdd(d
             , -Day(GetDate())
             , DateAdd(d, DateDiff(d, 0, GetDate() ), 0)))

The following snippet is used to strip the time portion from today's date:

DateAdd( d, DateDiff(d, 0, GetDate() ), 0 )

Update

Given your addition, you only need a small change the query above:

Select ...
From MyTable
Where Cast(Replace([Date],'M','') + '01' As DateTime)
    > DateAdd(m, -9
         , DateAdd(d
             , -Day(GetDate())
             , DateAdd(d, DateDiff(d, 0, GetDate() ), 0)))

Update

Given that you have now converted your date column to datetime, you can simplify your query:

Select ...
From MyTable
Where [Date] > DateAdd(m, -9, DateAdd(d
                               , -Day(GetDate())
                               , DateAdd(d, DateDiff(d, 0, GetDate() ), 0)))


SELECT TOP 9 [date]
FROM Mytable
WHERE [date] <= CONVERT(char(7),DATEADD(month, DATEDIFF(month, 0, GETDATE()), -1), 111)
ORDER BY [date] DESC
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜