Cross tab help (or something)

  • I am working with MS SQL Server (2000), and I have a table that looks something like this:

    Meter_NameLocal_Meter_IDDaily_HoursIntegrator_ValueReading_DateLegacy_ID
    AArea12471210/10/2006    25A
    BArea22448810/10/2006    25B
    CArea32464410/10/2006    42C
    DArea42451210/10/2006    54D
    EArea52425610/10/2006    62E
    FArea62478810/10/2006    71F
    AArea11672810/9/2006    25A
    BArea22050810/9/2006    25B
    CArea32266610/9/2006    42C
    DArea42453610/9/2006    54D
    EArea52428010/9/2006    62E
    FArea62481210/9/2006    71F

     

    I would like to run a query which results in something like this:

    Meter_NameLocal_Meter_IDLegacy_IDDaily_Hours 10/10/2006Integrator_Hours 10/10/2006Daily_Hours 10/9/2006Integrator_Hours 10/9/2006
    AArea125A2471216728
    BArea225B2448820508
    CArea342C2464422666
    DArea454D2451224536
    EArea562E2425624280
    FArea671F2478824812

     

    If I knew how to create field names from selected data on the fly, I might have gotten this. 

    Incidentally, there will be 90 days of "history" arranged to the right of each meter in the finished product.

    Thanks

    Rob

  • Perhaps you can do something with this. You can find the whole thread on http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=6216.

    CREATE PROCEDURE crosstab 
    @select varchar(8000),
    @sumfunc varchar(100), 
    @pivot varchar(100), 
    @table varchar(100),
    @where varchar(1000)=null
    AS
    
    DECLARE @sql varchar(8000), @delim varchar(1)
    SET NOCOUNT ON
    SET ANSI_WARNINGS OFF
    
    EXEC ('SELECT ' + @pivot + ' AS pivot INTO ##pivot FROM ' + @table + ' WHERE 1=2')
    EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + @pivot + ' FROM ' + @table + ' WHERE ' 
    + IsNull(@where,'1=1') + ' AND ' + @pivot + ' Is Not Null')
    
    SELECT @sql='',  @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' )
    
    SELECT @delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) ) 
    WHEN 0 THEN '' ELSE '''' END 
    FROM tempdb.information_schema.columns 
    WHERE table_name='##pivot' AND column_name='pivot'
    
    SELECT @sql=@sql + '''' + convert(varchar(100), pivot) + ''' = ' + 
    stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN ' 
    + @delim + convert(varchar(100), pivot) + @delim + ' THEN ' ) + ', ' FROM ##pivot
    
    DROP TABLE ##pivot
    
    SELECT @sql=left(@sql, len(@sql)-1)
    SELECT @select=stuff(@select, charindex(' FROM ', @select)+1, 0, ', ' + @sql + ' ')
    
    EXEC (@select)
    SET ANSI_WARNINGS ON

     


    Kindest Regards,

    erde

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply