Based on the following table
Title Jul-10 Aug-10 Sep-10 Oct-10 Nov-10 Dec-10 Jan-11 Feb-11 Mar-11 Apr-11 May-11 Jun-11
--------------------------------------------------------------------------------------------
A Null M1 Null M2 Null Null Null Null M3 Null Null Null
B Null M1 Null Null Null Null M2 Null Null Null Null Null
C Null Null Null Null Null M1 Null Null Null Null Null Null
How can i select only the columns between a certain range.
For instance if input variables are:
-------------------------------------
@start = 'Oct-10'
@end = 'Apr-11'
Then output will be:
Title Oct-10 Nov-10 Dec-10 Jan-11 Feb-11 Mar-11 Apr-11
-----------------------------------------------------------------
A M2 Null Null Null Null M3 Null
B Null Null Null M2 Null Null Null
C Null Null M1 Null Null Null Null
This is something that it makes more sense for the application to do than SQl. Do a:
Then let the application pivot the data. Typically applications can pivot data more efficiently than SQL can. Espcially when the number of columns vary each time you run it.
Here is an easier way to do your pivot, using a handy stored procedure named pivot_query (code is here, examples here ). This way you use your start and end date criteria to first limit the data to be pivoted, thus limiting the columns you get after the pivot.
The fn_MonthRange() function is a recursive CTE that provides a table of dates a month apart between the start and end dates, which you then OUTER join to your data. That will fill in any missing months.
(fn_DateRange() is similar, but works for arbitrary time segments like "every 15 minutes", every hour, every 3 days etc.)
Short answer is no. I have done some testing. I will give you the code to play with but because of how NULLs are handled with unpivot you will lose the contiguous range of months. They could be added back with the pivot, but that would require a numbers table, etc. Too much for me to do a 5:02! =)
You can generate the necessary SQL select statement, then use sp_executesql to run the query.
Here's an example of how to generate the month column names:
This gives me:
Incrementing the year could be done more explicitly. I took advantage of the automatic casting.
I only have access to SQL Server 2005, so there maybe a much better way in 2008.
It looks like the table is pivoted, by which I mean that the columns should probably be rows. This type of design is very human readable, but not very queryable.
Take a look at the UNPIVOT operator. You should be able to use it to get a data set with rows that you can filter against, and then when you're done you can PIVOT back into this format if you need to.
Here's an article: http://msdn.microsoft.com/en-us/library/ms177410.aspx
UNPIVOT performs almost the reverse operation of PIVOT, by rotating columns into rows.