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','/') 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
datecolumn 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:The following snippet is used to strip the time portion from today’s date:
Update
Given your addition, you only need a small change the query above:
Update
Given that you have now converted your
datecolumn todatetime, you can simplify your query: