sql - 比较 2 行和 2 列并找出差异
问题描述
原始数据
+--------+-------+---------------+---------------+---------------+---------------+---------------+---------------+
| RowNum | SeqNo | Col1 | Col2 | Col3 | Col4 | Col5 | Col6 |
+--------+-------+---------------+---------------+---------------+---------------+---------------+---------------+
| 1 | A123 | A | 'emptystring' | 'emptystring' | 'emptystring' | Z | 'emptystring' |
| 2 | A123 | 'emptystring' | B | 'emptystring' | 'emptystring' | 'emptystring' | D |
| 1 | B123 | 'emptystring' | 'emptystring' | C | 'emptystring' | 'emptystring' | 'emptystring' |
| 2 | B123 | 'emptystring' | 'emptystring' | 'emptystring' | D | 'emptystring' | 'emptystring' |
| 1 | C123 | A | 'emptystring' | B | 'emptystring' | 'emptystring' | 'emptystring' |
| 2 | C123 | 'emptystring' | A | 'emptystring' | B | 'emptystring' | A |
+--------+-------+---------------+---------------+---------------+---------------+---------------+---------------+
愿望结果:
+-------+---------------+----------+
| SeqNo | From_Value | To_Value |
+-------+---------------+----------+
| A123 | A | B |
| A123 | Z | D |
| B123 | C | D |
| C123 | 'emptystring' | A |
+-------+---------------+----------+
我怎样才能得到想要的结果?期望的结果是捕获所做的更改(基于期望的结果)。EmptyString 是空白 NOT NULL 只是空格。
SeqNo 是唯一编号,不会重复(在原始数据中)。
RowNum=1 = From_Value = Col1, Col3, Col5(这些不会改变)
RowNum=2 = To_Value = Col2, Col4, Col6(这些不会改变)
解决方案
create table #Raw (
RowNum int,
SeqNo nvarchar(20),
Col1 nvarchar(max),
Col2 nvarchar(max),
Col3 nvarchar(max),
Col4 nvarchar(max),
Col5 nvarchar(max),
Col6 nvarchar(max)
)
insert #Raw values
(1, 'A123', 'A', ' ', ' ', ' ', 'Z', ' '),
(2, 'A123', ' ', 'B', ' ', ' ', ' ', 'D'),
(1, 'B123', ' ', ' ', 'C', ' ', ' ', ' '),
(2, 'B123', ' ', ' ', ' ', 'D', ' ', ' '),
(1, 'C123', 'A', ' ', 'B', ' ', ' ', ' '),
(2, 'C123', ' ', 'A', ' ', 'B', ' ', 'A')
select f.SeqNo, f.Col1 [From_Value], t.Col2 [To_Value]
from #Raw f
join #Raw t on
t.SeqNo = f.SeqNo
and t.RowNum = 2
and f.Col1 <> t.Col2
where
f.RowNum = 1
union
select f.SeqNo, f.Col3 [From_Value], t.Col4 [To_Value]
from #Raw f
join #Raw t on
t.SeqNo = f.SeqNo
and t.RowNum = 2
and f.Col3 <> t.Col4
where
f.RowNum = 1
union
select f.SeqNo, f.Col5 [From_Value], t.Col6 [To_Value]
from #Raw f
join #Raw t on
t.SeqNo = f.SeqNo
and t.RowNum = 2
and f.Col5 <> t.Col6
where
f.RowNum = 1
drop table #Raw
推荐阅读
- swift - Swift:ARC 如何处理匿名对象?
- informatica - 使用 IICS 或 informatica 查找最高的员工并仅添加目标中的员工
- java - 创建 bean 时出错:没有符合条件的 bean,预期单个匹配 bean 但找到了 3
- database - GraphQL 模式可以用作数据库模式定义吗?
- php - 弹性搜索聚合查询 BadRequest400Exception
- azure - 个人 MS 帐户的 Azure 应用注册,无需添加外部用户
- c# - UDP Socket不会在android上接收数据
- python - Zeep 给出的错误查询请求太大。我必须拉〜100K记录
- flutter - Dart HTTP 请求列表
- java - 从运行在 tomcat 上的基于 spring 的应用程序中删除 JNDI 数据源配置