• Jeff Moden (10/25/2013)


    Hey Alex,

    Throw your test data into some readily consumable code and I'll be happy to show you how to do this.

    I'll be a little more charitable than Jeff (who usually even exceeds me in this area) and help you out with some sample data and a solution that might be close to what you need:

    WITH SampleData (Calls, [Minutes],[Month],[Name]) AS

    (

    SELECT 1,0,10,'NAME 1'

    UNION ALL SELECT 1,0,10,'NAME 4'

    UNION ALL SELECT 1,0,10,'NAME 4'

    UNION ALL SELECT 1,0,10,'NAME 4'

    UNION ALL SELECT 1,0,10,'NAME 2'

    UNION ALL SELECT 1,0,10,'NAME 3'

    UNION ALL SELECT 1,120,10,'NAME 3'

    UNION ALL SELECT 1,120,10,'NAME 4'

    UNION ALL SELECT 1,120,10,'NAME 4'

    UNION ALL SELECT 1,120,10,'NAME 4'

    UNION ALL SELECT 1,120,10,'NAME 3'

    UNION ALL SELECT 1,60,10,'NAME 2'

    UNION ALL SELECT 1,180,10,'NAME 3'

    UNION ALL SELECT 1,60,10,'NAME 1'

    UNION ALL SELECT 1,180,10,'NAME 1'

    UNION ALL SELECT 2,195,10,'NAME 2'

    UNION ALL SELECT 1,191,10,'NAME 1'

    )

    SELECT [Name]

    ,[Jan]=COUNT(CASE WHEN [Month]= 1 THEN Calls END)

    ,[Feb]=COUNT(CASE WHEN [Month]= 2 THEN Calls END)

    ,[Mar]=COUNT(CASE WHEN [Month]= 3 THEN Calls END)

    ,[Apr]=COUNT(CASE WHEN [Month]= 4 THEN Calls END)

    ,[May]=COUNT(CASE WHEN [Month]= 5 THEN Calls END)

    ,[Jun]=COUNT(CASE WHEN [Month]= 6 THEN Calls END)

    ,[Jul]=COUNT(CASE WHEN [Month]= 7 THEN Calls END)

    ,[Aug]=COUNT(CASE WHEN [Month]= 8 THEN Calls END)

    ,[Sep]=COUNT(CASE WHEN [Month]= 9 THEN Calls END)

    ,[Oct]=COUNT(CASE WHEN [Month]=10 THEN Calls END)

    ,[Nov]=COUNT(CASE WHEN [Month]=11 THEN Calls END)

    ,[Dec]=COUNT(CASE WHEN [Month]=12 THEN Calls END)

    ,[Total Calls]=COUNT(Calls)

    ,[Total Hours]=STUFF(CONVERT(VARCHAR(8), CAST(DATEADD(minute, SUM([Minutes])%60, 0) AS DATETIME), 108),1,2,

    SUM([Minutes]/60))

    FROM SampleData

    GROUP BY [Name];


    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