On 3?21?, ??9?42?, "rsjrny" <russlil...@yahoo..com> wrote:
> Please bear with me I am just learning SQL
>
> I have a table that contains the following data, these are monthly
> useage counts
>
> Prod Oct2007 Nov2006 Dec2006 Jan2007 Feb2007
> Mar2007
> XXXXV031 52 9 18 8 18 102
> XXXXV011 0 0 0 0 0 0
> XXXXV040 7 0 0 0 0 5
>
> Each month a new column is dynamically added to the table and access
> counts are
> maintained in the new month column. So next month a new column Apr2007
> will be
> added and the counts will increment there.
>
> I am unsuccessfully trying to write a select that will select only the
> last 4
> columns and maintain the actual column headers. So my results would
> look like:
>
> Prod Dec2006 Jan2007 Feb2007 Mar2007
> XXXXV031 18 8 18 102
> XXXXV011 0 0 0 0
> XXXXV040 0 0 0 5
>
> And next month if I executed the select I would see:
>
> Prod Jan2007 Feb2007 Mar2007 Apr2007
> XXXXV031 8 18 102 n
> XXXXV011 0 0 0 n
> XXXXV040 0 0 5 n
>
> any help would be greatly appreciated
you can use dynamic sql like this:
declare @sql nvarchar(4000)
select @sql = ''
select @sql = @sql + '
select ' +
month(dataadd(month,getdate(),-4))+year(dataadd(month,getdate(),-4))
....
+'from
table
'