Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server convert columns to rows

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   C       C1      X       X

I want to compare them and display in a the following table if the value has changes.

Id  Column  Value   Pvalue
1   Value2  V       V1
2   Value1  B       B1
2   Value2  W       W1
3   Value1  C       C1

Is it possible in SQL 2008 without looping each column?

like image 977
developer Avatar asked Feb 26 '13 14:02

developer


2 Answers

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

like image 73
Taryn Avatar answered Sep 30 '22 16:09

Taryn


Here is an easy way:

SELECT  Id, 
        'Value1' [Column],
        Value1 Value,
        PValue1 PValue
FROM YourTable
WHERE ISNULL(Value1,'') != ISNULL(PValue1,'')
UNION ALL
SELECT  Id, 
        'Value2' [Column],
        Value2 Value,
        PValue2 PValue
FROM YourTable
WHERE ISNULL(Value2,'') != ISNULL(PValue2,'')
like image 39
Lamak Avatar answered Sep 30 '22 18:09

Lamak