首页 > 解决方案 > 比较 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(这些不会改变)

标签: sqlsql-server

解决方案


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

推荐阅读