可以使用CROSS APPLY
来unpivot的数据:
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;
见SQL Fiddle with Demo。
只是因为我喜欢使用支点功能,下面是一个使用和版本均逆转置的支点函数来获得结果:
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
见SQL Fiddle with Demo
+1,因为我不知道你可以用这种方式使用CROSS APPLY! – 2013-02-26 14:23:02
+1有蓝色......我的意思是提供一个SQL小提琴。 – Kermit 2013-02-26 14:25:30
谢谢,它非常有用。 – developer 2013-02-26 14:29:06