Home Forums SQL Server 2008 T-SQL (SS2K8) converting columns to rows comparing multiple records RE: converting columns to rows comparing multiple records

  • Hi, me again

    After doing some gym i came up with the following solution:

    ;with aa as

    (select

    id,

    record_type,

    old.property,

    old.value

    FROM

    (select

    id,

    record_type,

    convert(varchar(250),sex) sex,

    convert(varchar(250),age) age

    from

    #test) data

    UNPIVOT

    (value FOR property IN (sex,age)) old)

    select

    old.id,

    old.property,

    old.value old_value,

    new.value new_value

    from

    aa old

    inner join aa new on new.id = old.id and new.property = old.property and old.record_type <> new.record_type

    where

    old.id = 1 and

    old.record_type= 'old'

    in case there where more than 2 records per key i'd probably have to use row_number() to filter the resultset

    Hope this works for me; i'll do some testing