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

  • Dwight617 (9/2/2012)


    Sorry dwain .. data

    INSERT INTO [Table]

    SELECT 1234, 1, 'True', 'False', 'False', 2, 'False', 'False', 'False', 3, 'True', 'True', 'True', 4, 'False', 'False', 'False'

    One other complication, looking to filter and only show column1,2,3,4 When 2 or 3, or 4 = 'True'

    Result should be something like

    recordid column1, column2, column3, column4

    1234 1 true f f

    1234 3 true true true

    Looking at your cross apply now. Thanks for the link hadn't seen that.

    Ah! Clarity!

    DECLARE @t TABLE (

    [record_id] [int] 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,

    [Column1c] [int] NULL,

    [Column2c] [nvarchar](30) NULL,

    [Column3c] [nvarchar](30) NULL,

    [Column4c] [nvarchar](30) NULL,

    [Column1d] [int] NULL,

    [Column2d] [nvarchar](30) NULL,

    [Column3d] [nvarchar](30) NULL,

    [Column4d] [nvarchar](30) NULL

    )

    INSERT INTO @t

    SELECT 1234, 1, 'True', 'False', 'False', 2, 'False', 'False', 'False', 3, 'True', 'True', 'True', 4, 'False', 'False', 'False'

    SELECT record_id, col1, col2, col3, col4

    FROM @t

    CROSS APPLY (

    VALUES (Column1a, Column2a, Column3a, Column4a)

    ,(Column1b, Column2b, Column3b, Column4b)

    ,(Column1c, Column2c, Column3c, Column4c)

    ,(Column1d, Column2d, Column3d, Column4d)) alphas(col1, col2, col3, col4)

    WHERE col2 = 'True' OR col3 = 'True' OR col4 = 'True'

    Edit: Minor but important correction to the query.


    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