SQL Server convert columns to rows

感情迁移 提交于 2019-11-28 12:18:53

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

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,'')

How about using a union:

SELECT * FROM
    (SELECT Id, 'Value1' [Column], Value1 [Value], PValue1 [PValue]
    FROM table_name
    UNION ALL
    SELECT Id, 'Value2' [Column], Value2 [Value], PValue2 [PValue]
    FROM table_name)tmp
WHERE Value != PValue
ORDER BY Id

Finally, and for completeness, there is an UNPIVOT command. However, since you have two columns you want to unpivot, it'd probably be simpler to use one of the other solutions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!