SQL Server convert columns to rows

后端 未结 4 1655
挽巷
挽巷 2020-12-10 18:08

I have a sql table with current value and previous value.

Id  Value1  PValue1 Value2  PValue2
1   A       A       V       V1
2   B       B1      W       W1
3         


        
4条回答
  •  我在风中等你
    2020-12-10 18:27

    You can use a CROSS APPLY to unpivot the data:

    SELECT t.id,
      x.Col,
      x.Value,
      x.PValue
    FROM YourTable t
    CROSS APPLY 
    (
        VALUES
            ('Value1', t.Value1, t.PValue1),
            ('Value2', t.Value2, t.PValue2)
    ) x (Col, Value, PValue)
    where x.Value <> x.PValue;
    

    See SQL Fiddle with Demo.

    Just because I love using the pivot function, here is a version that uses both the unpivot and the pivot functions to get the result:

    select id, 
      colname,
      value,
      pvalue
    from
    (
      select id, 
        replace(col, 'P', '') colName,
        substring(col, 1, PatIndex('%[0-9]%', col) -1) new_col,  
        val
      from yourtable
      unpivot
      (
        val
        for col in (Value1, PValue1, Value2, PValue2)
      ) unpiv
    ) src
    pivot
    (
      max(val)
      for new_col in (Value, PValue)
    ) piv
    where value <> pvalue
    order by id
    

    See SQL Fiddle with Demo

提交回复
热议问题