我与当前值和前值SQL表。
Id Value1 PValue1 Value2 PValue2
1 A A V V1
2 B B1 W W1
3 C C1 X X
我想他们和显示一个比较在下表中,如果值已经改变。
Id Column Value Pvalue
1 Value2 V V1
2 Value1 B B1
2 Value2 W W1
3 Value1 C C1
是否有可能在2008年SQL没有循环每列?
您可以使用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拨弄演示 。
只是因为我喜欢使用的旋转功能,这里是同时使用逆透视和枢轴函数来获得结果的版本:
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拨弄演示
这里有一个简单的方法:
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,'')
如何利用工会:
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
最后,为了完整性,有一个UNPIVOT命令。 但是,因为你必须要UNPIVOT两列,它很可能是简单的使用了另一种解决方案。