I have a table named Employee_audit with following schema,
| emp_audit_id | eid | name | salary |
|---|---|---|---|
| 1 | 1 | Daniel | 1000 |
| 2 | 1 | Dani | 1000 |
| 3 | 1 | Danny | 3000 |
My goal is to write a SQL query which will return in following format, considering the first row also as changed value from null.
| columnName | oldValue | newValue |
|---|---|---|
| name | null | Daniel |
| salary | null | 1000 |
| name | Daniel | Dani |
| name | Dani | Danny |
| salary | 1000 | 3000 |
I have written the below SQL query,
WITH cte AS
(
SELECT empid,
name,
salary,
rn=ROW_NUMBER()OVER(PARTITION BY empid ORDER BY emp_audit_id)
FROM Employee_audit
)
SELECT oldname=CASE WHEN c1.Name=c2.Name THEN '' ELSE C1.Name END,
newname=CASE WHEN c1.Name=c2.Name THEN '' ELSE C2.Name END,
oldsalary=CASE WHEN c1.salary=c2.salary THEN NULL ELSE C1.salary END,
newsalary=CASE WHEN c1.salary=c2.salary THEN NULL ELSE C2.salary END
FROM cte c1 INNER JOIN cte c2
ON c1.empid=c2.empid AND c2.RN=c1.RN + 1
But it gives the result in following format
| oldname | newname | oldsalary | newsalary |
|---|---|---|---|
| Daniel | Dani | null | null |
| Dani | Danny | 1000 | 3000 |
Could you please answer me, how can I get the required result.