Home Forums SQL Server 2012 SQL Server 2012 - T-SQL Unpivot okay, but how do I extract one more piece of data from the column? RE: Unpivot okay, but how do I extract one more piece of data from the column?

  • Try this.

    --USE <your DB name>;

    GO

    IF object_id(N'dbo.BadTox', 'U') IS NOT NULL

    DROP TABLE [dbo].[BadTox];

    GO

    CREATE TABLE [dbo].[BadTox](

    [PatientID] [int] NULL,

    [Cycle] [tinyint] NULL,

    [ALOPECIA] [tinyint] NULL,

    [Causality1] [tinyint] NULL,

    [Relatedness1] [tinyint] NULL,

    [BLOOD] [tinyint] NULL,

    [Causality2] [tinyint] NULL,

    [Relatedness2] [tinyint] NULL,

    [BRAIN] [tinyint] NULL,

    [Causality3] [tinyint] NULL,

    [Relatedness3] [tinyint] NULL

    );

    INSERT [dbo].[BadTox] VALUES

    (100,110, 1, 2, 3, 11, 12, 13, 21, 22, 23)

    ,(100,111, 2, 3, 4, 12, 13, 14, 22, 23, 24)

    ,(200,111, 3, 4, 5, 13, 14, 15, 23, 24, 25);

    DECLARE @object_id INT;

    SET @object_id = object_id(N'dbo.BadTox');

    DECLARE @cmd VARCHAR(8000) = 'SELECT ups.PatientID

    , ups.Cycle

    , CrossApplied.SymptomName

    , CrossApplied.Toxicity

    , CrossApplied.Causality

    , CrossApplied.Relatedness

    FROM [dbo].[BadTox] ups

    CROSS APPLY (VALUES ';

    SET @cmd += STUFF(

    (SELECT ',('''+name+''','+ name

    +', Causality'+

    CAST(ROW_NUMBER() OVER (ORDER BY column_id) AS VARCHAR(2))

    +', Relatedness'+

    CAST(ROW_NUMBER() OVER (ORDER BY column_id) AS VARCHAR(2))

    + ')'

    --, Causality_N_Relatedness_suffix =row_number() over (order by column_id)

    FROM sys.all_columns

    WHERE name = UPPER(name) COLLATE SQL_Latin1_General_CP1_CS_AS

    AND object_id = @object_id

    FOR XML PATH('') )

    ,1,1,'');

    SET @cmd += ') CrossApplied (SymptomName, Toxicity, Causality, Relatedness);';

    EXEC (@cmd);

    The assumption is that Causality and Relatedness columns names follow Causality[n], Relatedness[n] pattern.

    Hope it helps.