PIVOT Tables issues

  • Hi,

    I have the following table which stores disk space info.

    [dbo].[Monitor_DiskSpace]

    [TableID] [int] IDENTITY(1,1) NOT NULL,

    [ServerName] [varchar](50) NULL,

    [Drive] [varchar](50) NULL,

    [MB_Free] [varchar](10) NULL,

    [TotalSize] [varchar](10) NULL,

    [RecordDate] [datetime] NULL,

    I need to extract the free space % using MB_Free and TotalSize and I need it to be presented like so;

    [RecordDate] 'C' 'D' 'E' 'F'

    ----------------------------------------------------------------------------------

    2011-12-20 14:40:14.380 10.01% 12.23% 23.01% 13.56%

    I've been trying to use a Pivot table but I keep hitting issue with the fact MB_Free and TotalSize are varchars and Pivot tables may not be the right approach.

    SELECT TOP 100 P.RecordDate

    , IsNull(P.[1], 0) as 'C'

    , IsNull(P.[2], 0) as 'D'

    , IsNull(P.[3], 0) as 'E'

    , IsNull(P.[4], 0) as 'G'

    FROM (SELECT RecordDate

    , Drive

    --, cast((cast(MB_Free AS decimal(7,2))/ CAST (TotalSize AS decimal(7,2)))*100 as numeric(10,2)) as [%Free]

    ,CAST(MB_Free AS INT) / CAST(TotalSize AS INT) as [%Free]

    FROM [DBAMain].[dbo].[Monitor_DiskSpace]

    WHERE ServerName = 'NTH01A\NTH01A'

    AND Drive IN ('c','D','E','G')

    )

    I PIVOT (

    SUM ([%Free]) FOR DRIVE IN ([1], [2], [3], [4], [5], [6], [7], [8], [9])

    ) AS P

    ORDER BY RecordDate Asc

    Any help gratefully received.

    Thanks, Phil

  • Try googling "SQL Crosstabs" or look at these articles from Jeff Moden:

    http://qa.sqlservercentral.com/articles/T-SQL/63681/

    http://qa.sqlservercentral.com/articles/Crosstab/65048/

    If you provide sample data, I'm sure someone can provide you a working, tested solution from the DDL and expected results you posted.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

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

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