Home Forums SQL Server 2008 T-SQL (SS2K8) Unpivot question, struggling with data please help RE: Unpivot question, struggling with data please help

  • You're a bit scant on sample data, but we'll take a stab at it anyway. You can see in this example how to UNPIVOT single or multiple columns, so you should be able to manipulate it to get it where you need it to be.

    DECLARE @t TABLE (

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

    [Column1a] [int] NULL,

    [Column2a] [nvarchar](30) NULL,

    [Column3a] [nvarchar](30) NULL,

    [Column4a] [nvarchar](30) NULL,

    [Column1b] [int] NULL,

    [Column2b] [nvarchar](30) NULL,

    [Column3b] [nvarchar](30) NULL,

    [Column4b] [nvarchar](30) NULL)

    INSERT INTO @t

    SELECT 1, 'A', 'B', 'C', 2, 'D', 'E', 'F'

    SELECT record_id, num, alpha1, alpha2

    FROM @t

    CROSS APPLY (

    VALUES (Column1a), (Column1b)) nums(num)

    CROSS APPLY (

    VALUES (Column2a, Column2b), (Column3a, Column3b), (Column4a, Column4b)) alphas(alpha1, alpha2)

    You can read about the CROSS APPLY VALUES approach to UNPIVOT here:

    http://www.sqlservercentral.com/articles/CROSS+APPLY+VALUES+UNPIVOT/91234/

    The discussion thread has some good information on performance compared to UNPIVOT.


    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