Ori Data
+--------+-------+---------------+------------+--------+--------------+-------+
| RowNum | SeqNo | Name | NameReason | Gender | GenderReason | ID |
+--------+-------+---------------+------------+--------+--------------+-------+
| 1 | A123 | IronMan | | P | | E8888 |
| 2 | A123 | CaptainMarvel | A | L | A | E8888 |
| 3 | A123 | Yoooo | | | | E8888 |
| 4 | A123 | Heyyy | | | | E8888 |
| 1 | B456 | Hey | | | | D2222 |
| 2 | B456 | DOTS | A | | | D2222 |
| 1 | C1234 | Hulk | | | | E8989 |
| 2 | C1234 | Cap | | | | E8989 |
| 3 | C1234 | Hat | | | | E8989 |
+--------+-------+---------------+------------+--------+--------------+-------+
Result I Want
+-------+-------+---------+---------------+----------+--------+
| SeqNo | ID | ColName | From_Value | To_Value | Reason |
+-------+-------+---------+---------------+----------+--------+
| A123 | E8888 | Name | CaptainMarvel | IronMan | A |
| A123 | E8888 | Gender | L | P | A |
| B456 | D2222 | Name | DOTS | Hey | A |
| C1234 | E8989 | Name | Cap | Hulk | |
+-------+-------+---------+---------------+----------+--------+
Query:
select a.rownum, a.seqno, a.name, a.id,
b.*
from #A a cross apply
( values ('Name', NameReason)
('Gender', GenderReason)
) b (colname, Reason)
where reason is not null
Note: Want to find the changes. RowNum=1
is the latest update (To_Value
), RowNum=2
(From_Value
). Rownum already filter the top updated result (rownumber () over (partitition)
. I just need rownum=2(from_Value), rownum=1(to_value) others ignore, because 1 application can update 100times, i just need find the latest changes will do.
From the query above, how can I modify to the result I want? How can I add from_value and to_value, reason?